package eecs.umich.threegtest;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;


public class threegtest extends Activity {
	
	////////////////////////////Constants - mhayter////////////////////////////
    //labeled as static final ints
    private static final int PORT_WHOAMI = 5000;
    private static final int PORT_BT = 6881;
    private static final int PORT_BT_RAND = 5005;
    private static final int PORT_HTTP = 80;
    private static final int PORT_THRU_DOWN = 5001;
    private static final int PORT_THRU_UP = 5002;
    private static final int PORT_DNS_TCP = 53;
    private static final int PORT_DNS_UDP = 53;
    private static final int PORT_CACHING = 6000;
    private static final int PORT_CONTROL = 5004;
    
    private static final int[] ports = new int [] {21, 22, 25, 53, 110, 135, 139, 143, 161, 443, 445, 465, 585, 587, 993, 995, 5060};
    private static final String[] portnames = new String[] {"FTP", "SSH", "SMTP", "DNS", "POP", "RPC", "NETBIOS", "IMAP", "SNMP", "HTTPS", "SMB", "SMTP SSL", "Secure IMAP", "Auth SMTP", "IMAP SSL", "POP SSL", "SIP"};
    
    //IPs
    private static final String umichserverIP1 = "141.212.111.219";
    private static final String ReachserverIP = "141.212.111.182";
    private static final String httpserverIP = "141.212.111.219";
    private static final String ALTERNATIVE_IP = "141.212.111.182";
    
    private static final String filename = "file.txt";
    private static final String TAG = "PR";
    
    private static final String[] popDNSnames = new String[] {
        "www.google-analytics.com", "p.admob.com", "www.facebook.com", "maps.yahoo.com",
        "mt2.google.com", "us.js2.yimg.com", "en.wikipedia.org", "sports.espn.go.com",
        "www.weather.com", "maps.google.com", "m.webtrends.com", "ads.bluelithium.com",
        "img.turn.com", "mt3.google.com", "static.mobile.espn.go.com", "www.wikipedia.org",
        "xhtml.weather.com", "us.mc599.mail.yahoo.com", "i.cdn.turner.com", "i.imwx.com",
        "login.live.com", "m.myspace.com", "www.cnn.com", "home.mobile.msn.com",
        "mobile.live.com", "ads.yimg.com", "mail.yahoo.com", "metrics.nba.com",
        "www.live.com", "www.nba.com", "s.ytimg.com", "ad.trafficmp.com",
        "i1.ytimg.com", "mobile.msn.com", "gfx1.hotmail.com", "adopt.euroclick.com",
        "m.facebook.com", "m.go.com", "content.dl-rms.com", "view.atdmt.com",
        "aglobal.go.com", "www.google.com", "upload.wikimedia.org", "r1.beta.ace.advertising.com",
        "www.myspace.com", "a248.e.akamai.net", "pr.atwola.com", "us.i1.yimg.com",
        "ia.media-imdb.com", "bp.specificclick.net", "www.blogger.com", "www.msn.com",
        "www.aolcdn.com", "mail.live.com", "uac.advertising.com", "www.go.com",
        "action.mathtag.com", "m.live.com", "media.adrevolver.com", "m1.2mdn.net",
        "mt1.google.com", "www.hotmail.com", "streak.espn.go.com", "i.media-imdb.com",
        "m.youtube.com", "ll.atdmt.com", "ad.turn.com", "cdn.fastclick.net",
        "www.amazon.com", "ssl.google-analytics.com", "blstb.msn.com", "mobile.microsoft.com",
        "www.mapquest.com", "ia.imdb.com", "core.insightexpressai.com", "i4.ytimg.com",
        "adsatt.go.starwave.com", "m.espn.go.com", "m.cnn.com", "log.go.com"
    };
    
    
    ///////////////////////////////////////////////////////////////////////
    
    
    int npopDNS = 80;
    int replycode;
    String netinfoS;
    boolean thread1doneflag = false;
    boolean thread2doneflag = false;
    boolean pingflag = true;
    boolean inflag = false;
    String localip, seenip;
    
    //Connectivity tester mhayter
    ConnectivityTester tester;
    
    //Important IP changeable 
    private static String serverIP = "141.212.111.182";
    
    ///////////////////////////////// UI ////////////////////////////////////
    Intent myIntent;
    static int mProgressStatus = 0;
    ProgressBar mProgress;
    TextView t1, t2, t3;
    PowerManager.WakeLock wl;;
    Button button, button2;
    static int bit = 0;
    int roundrunning = 0;
    int actualroundrunning = 0;
    boolean isrunning;
    ListView lvw;
    ArrayAdapter<String> adapter;
    Handler mHandler = new Handler();
    String btblockedstage;
    
    //////////////////////////////// END UI //////////////////////////////////
    
    //////////////////////////////////// SERVERS AND PORTS ///////////////////
    //mhayter 6-30-2010
    
    //private String serverIP = "localhost";
    String prefix = null;
    boolean stopflag = false;
    static int completed = 0;
    
    //String umichserverIP2 = "141.212.2.81";
    int nlandmarkservers = 100;
    String filename1 = "UMLogger.txt";
    String[] landmarkservers = new String[ 100 ];
    String[] popDNSaddresses = new String[ 500 ];


    /*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          System.exit(1);
        }  
        return super.onKeyDown(keyCode,event);
    } */ 
    
    // results
    String message;
    String message1;
    String result;
    
    //mhayter
    //String deviceID;
    Context context;
    long runID;
    //mhayter
    //String networkOperator;
    //mhayter
    //int networktype;
    //mhayter
    //int wifi_or_3G;
    
    Location location;
    String infoS;
    
    //mhayter
    //boolean network_status;
    boolean DNSUMICH, DNSTCP, NATexistence, BTblocking, DNSGOOGLE;
    int rports = 0;
    int reachi = 0;
    boolean [] REACHB = new boolean[ 17 ];
    char [] REACHBst = new char[ 17 ];
    boolean [] DNSpop = new boolean[ npopDNS ];
    long [] DNSlatencies = new long[ npopDNS ];


    long DNSlat;
    long DNSlatyes;
    double lat, longt;
    String signalservers = "";
    long[] latencyservers = new long[ 2 ];
    int[] lossrateservers = new int[ 2 ];
    long[] latencylandmarkservers = new long[ nlandmarkservers ];
    int[] lossratelandmarkservers = new int[ nlandmarkservers ];
    long[] synacklandmarkservers = new long[ nlandmarkservers ];
    long[] getslandmarkservers = new long[ nlandmarkservers ];
    long[] gettlandmarkservers = new long[ nlandmarkservers ];
    int completepinglandrmarkservers;
    int successpinglandmarkservers;
    int avgpinglandmarkservers;
    int successhttplandmarkservers;
    int avghttplandmarkservers;
    int avghttplandmarkservers2;
    private static final int cachtimes = 10;
    int ncachingsuccess;
    int ncachingcomplete;
    boolean cachflag = false;
    boolean compressionflag = false;
    long downlinksize, uplinksize, downlinktime;
    boolean DNSgoogle = false;
    String PhoneNo;
    Socket RtcpSocket = null;
    DataOutputStream Ros = null;
    DataInputStream Ris = null;
    boolean Rflag = false;
    String[] mStrings = new String[ 14 ];
    String lin, mps;
    int imps, k;
    boolean hdoneflag;
    String[] results = new String[ 20 ];
    
    public void onStart() {
        stopflag = false;
        checkifrunning();

        if ( isrunning )
            new file_thread().start();

        super.onStart();
    }
    
    class file_thread extends Thread {
        public void run() {
            imps = 0;
            FileInputStream reader = null;
            this.setPriority( MAX_PRIORITY );
            byte[] buffer = new byte[ 10 ];
            char c;
            hdoneflag = false;
            mHandler.post( new Runnable() {
                               public void run() {
                                   adapter.clear();
                                   hdoneflag = true;
                               }
                           }

                         );
            Log.d( TAG, "cleared" );

            while ( hdoneflag == false ) {}

            try {
                reader = openFileInput( filename );
                hdoneflag = false;
                int actualgotcount = 0;

                while ( reader.available() != 0 ) {
                    lin = "";

                    do {
                        reader.read( buffer, 0, 1 );
                        c = ( char ) buffer[ 0 ];

                        if ( c != '\n' )
                            lin += c;
                    }
                    while ( c != '\n' );

                    results[ actualgotcount++ ] = lin;

                    mps = "";

                    do {
                        reader.read( buffer, 0, 1 );
                        c = ( char ) buffer[ 0 ];

                        if ( c != '\n' )
                            mps += c;
                    }
                    while ( c != '\n' );

                    imps = new Integer( mps );
                }

                hdoneflag = false;
                mHandler.post( new Runnable() {
                                   public void run() {
                                       adapter.clear();
                                       hdoneflag = true;
                                   }
                               }

                             );

                while ( hdoneflag == false ) {}

                for ( k = 0;k < actualgotcount;k++ ) {
                    hdoneflag = false;
                    mHandler.post( new Runnable() {
                                       public void run() {
                                           adapter.add( results[ k ] );
                                           lvw.setAdapter( adapter );
                                           lvw.setBackgroundColor( R.color.black );
                                           hdoneflag = true;
                                       }
                                   }

                                 );

                    while ( hdoneflag == false ) {}

                }

                hdoneflag = false;

                mHandler.post( new Runnable() {
                                   public void run() {
                                       mProgress.setProgress( imps );
                                       t2.setText( "" + imps + "% Complete" );
                                       hdoneflag = true;
                                   }
                               }

                             );

                while ( hdoneflag == false ) {}

                reader.close();
            }
            catch ( Exception e ) {
                Log.d( TAG, " UP  exception " + e.toString() );
            }


            DatagramSocket killSocket = null;

            try {
                killSocket = new DatagramSocket();
                killSocket.setReuseAddress( true );
                FileOutputStream fOut1 = null;
                OutputStreamWriter out1 = null;
                fOut1 = openFileOutput( "uiprint.txt", MODE_WORLD_READABLE );
                out1 = new OutputStreamWriter( fOut1 );
                out1.write( "" + killSocket.getLocalPort() + "\n" );
                out1.close();
                fOut1.close();
            }
            catch ( Exception e ) {
                Log.d( TAG, "down exception " + e.toString() );
            }

            do {
                try {
                    byte[] recvbuf = new byte[ 1024 ];
                    DatagramPacket rpacket = new DatagramPacket( recvbuf, recvbuf.length );
                    Log.d( TAG, "cleared" );
                    killSocket.receive( rpacket );
                    String reply = new String( rpacket.getData(), rpacket.getData().length );
                    lin = "";
                    int i = 0;

                    do {
                        c = reply.charAt( i++ );

                        if ( c != '!' )
                            lin += c;
                        else
                            break;
                    }
                    while ( true );

                    imps = new Integer( lin );

                    if ( imps == 1000 ) {
                        killSocket.close();
                        return ;
                    }

                    if ( imps == 1001 ) {
                        killSocket.close();
                        hdoneflag = false;
                        mHandler.post( new Runnable() {
                                           public void run() {
                                               t3.setText( "Run complete, press button to restart app" );
                                               button.setText( "start" );
                                               hdoneflag = true;
                                           }
                                       }

                                     );

                        while ( hdoneflag == false ) {}

                        return ;
                    }

                    lin = "";
                    int j;

                    for ( j = 0;j < imps;j++ ) {
                        lin += reply.charAt( j + i );
                    }

                    hdoneflag = false;
                    mHandler.post( new Runnable() {
                                       public void run() {
                                           if ( lin.charAt( 0 ) == 'N' && lin.charAt( 1 ) == 'e' )
                                               adapter.clear();

                                           adapter.add( lin );

                                           lvw.setAdapter( adapter );

                                           hdoneflag = true;
                                       }
                                   }

                                 );

                while ( hdoneflag == false ) {}

                    i += j;

                    lin = "";

                    do {
                        c = reply.charAt( i++ );

                        if ( c != '!' )
                            lin += c;
                        else
                            break;
                    }
                    while ( true );

                    imps = new Integer( lin );

                    hdoneflag = false;

                    mHandler.post( new Runnable() {
                                       public void run() {
                                           mProgress.setProgress( imps );
                                           t2.setText( "" + imps + "% Complete" );
                                           hdoneflag = true;
                                       }
                                   }

                                 );

                    while ( hdoneflag == false ) {}

                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    Log.v( TAG, "in file exception " + e.toString() );
                    e.printStackTrace();
                }

            }
            while ( true );
        }
    }

    @Override
    public void onStop() {
        sendudpmessage( "uiprint.txt", "1000!" );
        super.onStop();
    }

    long repeattime;
    @Override
    public boolean onCreateOptionsMenu( Menu menu ) {
        super.onCreateOptionsMenu( menu );
        //menu.add(0, 0, 0,"No repeatitions");
        //menu.add(0, 1, 0,"Repeat every 10 minutes");
        //menu.add(0, 2, 0,"Repeat every 1 hour");
        //menu.add(0, 3, 0,"Repeat every 6 hour");
        //menu.add(0, 4, 0,"Repeat every 12 hour");
        //menu.add(0, 5, 0,"Repeat every 24 hours");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        super.onOptionsItemSelected( item );

        switch ( item.getItemId() ) {
        case 0:
            repeattime = 0;
            break;
        case 1:
            repeattime = 600000;
            break;
        case 2:
            repeattime = 3600000;
            break;
        case 3:
            repeattime = 21600000;
            break;
        case 4:
            repeattime = 43200000;
            break;
        case 5:
            repeattime = 86400000;
            break;
        default:
            break;
        }

        checkifrunning();

        try {
            FileOutputStream fOut1 = null;
            OutputStreamWriter out1 = null;
            fOut1 = openFileOutput( "repeatfile.txt", MODE_WORLD_READABLE );
            out1 = new OutputStreamWriter( fOut1 );
            out1.write( "" + repeattime + "\n" );
            out1.close();
            fOut1.close();
        }
        catch ( Exception e ) {}

        checkifrunning();

        if ( isrunning ) {
            mHandler.post( new Runnable() {
                               public void run() {
                                   t3.setPadding( 40, 5, 10, 5 );
                                   t3.setText( "App is running, press button to stop" );
                               }
                           }

                         );
        }

        return false;
    }


    @Override
    public void onCreate( Bundle savedInstanceState ) {
    	Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>>>>>> STARTING APPLICATION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        super.onCreate( savedInstanceState );
        
        //set up 
        tester = new ConnectivityTester(this);
        
        //Internet Detection Dialog
        tester.detectInternetConnection();
       
        
        Log.d(TAG, "----------------- AFTER ALERT DIALOGBOX -------------------------");
        //create user interface
        setContentView( R.layout.main );
        button = ( Button ) findViewById( R.id.Button01 );
        t1 = ( TextView ) findViewById( R.id.textview1 );
        t2 = ( TextView ) findViewById( R.id.textview2 );
        t3 = ( TextView ) findViewById( R.id.textview3 );
        location();
        Log.d( TAG, "\n\nNEw runnnnnnnnnnn \n\n\n\n" );
        
        mProgress = ( ProgressBar ) findViewById( R.id.progress_bar );
        mProgress.setPadding( 10, 5, 10, 5 );
        t1.setPadding( 30, 5, 10, 5 );
        t2.setPadding( 108, 5, 10, 5 );
        t3.setPadding( 90, 5, 10, 5 );
        
        t1.setHintTextColor( 2 );
        t2.setHintTextColor( 2 );
        t3.setHintTextColor( 2 );
        
        t2.setText( "" + 0 + "% Complete" );
        
        lvw = ( ListView ) findViewById( R.id.list );
        mStrings[ 0 ] = "h";
        adapter = new ArrayAdapter<String>( this, R.layout.simple_list_item_1 );

        adapter.add( "" );
        lvw.setAdapter( adapter );
        t1.setText( "This app takes 2 to 3 minutes to complete all tests.Please be patient! Results saved to file UMLogger.txt in sdcard" );

        isrunning = false;
        checkifrunning();
        long repeat;

        if ( isrunning == false ) {
            button.setText( "start" );
            t3.setText( "Press button to start" );
            mProgressStatus = 0;
            mProgress.setProgress( mProgressStatus );
        }
        else if ( ( repeat = getrepeattime() ) != -1 ) {
            t3.setPadding( 40, 5, 10, 5 );
            t3.setText( "App is running, press button to stop" );
            button.setText( "stop" );
        }
        else {
            t3.setPadding( 10, 5, 10, 5 );
            t3.setText( "Press Menu to select how often do you want the app to run" );
            button.setText( "stop" );
        }

        context = this;
        button.setOnClickListener( new View.OnClickListener() {
                                       public void onClick( final View view ) {
                                           checkifrunning();

                                           if ( isrunning ) {
                                               mProgressStatus = 0;
                                               completed = 0;
                                               mHandler.post( new Runnable() {
                                                                  public void run() {

                                                                      stopflag = true;
                                                                      sendudpmessage( "uiprint.txt", "1000!" );
                                                                      mHandler.post( new Runnable() {
                                                                                         public void run() {
                                                                                             t3.setPadding( 90, 5, 10, 5 );
                                                                                             t3.setText( "Press button to start" );
                                                                                             mProgress.setProgress( 0 );
                                                                                             adapter.clear();
                                                                                             t2.setText( "" + 0 + "% Complete" );
                                                                                             button.setText( "start" );
                                                                                             new write_to_file().start();
                                                                                         }
                                                                                     }

                                                                                   );

                                                                      try {
                                                                          FileOutputStream fOut1 = null;
                                                                          OutputStreamWriter out1 = null;
                                                                          fOut1 = openFileOutput( "versionfile.txt", MODE_WORLD_READABLE );
                                                                          out1 = new OutputStreamWriter( fOut1 );
                                                                          out1.write( "0" + "\n" );
                                                                          out1.close();
                                                                          fOut1.close();
                                                                      }
                                                                      catch ( Exception e ) {
                                                                          Log.d( TAG, "down exception " + e.toString() );
                                                                      }

                                                                      try {
                                                                          FileOutputStream fOut1 = null;
                                                                          OutputStreamWriter out1 = null;
                                                                          fOut1 = openFileOutput( filename, MODE_WORLD_READABLE );
                                                                          out1 = new OutputStreamWriter( fOut1 );
                                                                          out1.close();
                                                                          fOut1.close();
                                                                      }
                                                                      catch ( Exception e ) {
                                                                          Log.d( TAG, "down exception " + e.toString() );
                                                                      }

                                                                      sendudpmessage( "killsocket.txt", "kill" );
                                                                  }
                                                              }

                                                            );
                                           }
                                           else {
                                               mHandler.post( new Runnable() {
                                                                  public void run() {
                                                                      t3.setPadding( 40, 5, 10, 5 );
                                                                      t3.setText( "App is running, press button to stop" );
                                                                      button.setText( "stop" );
                                                                  }
                                                              }

                                                            );

                                               try {
                                                   FileOutputStream fOut1 = null;
                                                   OutputStreamWriter out1 = null;
                                                   fOut1 = openFileOutput( filename, MODE_WORLD_READABLE );
                                                   out1 = new OutputStreamWriter( fOut1 );
                                                   out1.close();
                                                   fOut1.close();
                                                   fOut1 = openFileOutput( "repeatfile.txt", MODE_WORLD_READABLE );
                                                   out1 = new OutputStreamWriter( fOut1 );
                                                   out1.write( "-1" + "\n" );
                                                   out1.close();
                                                   fOut1.close();
                                               }
                                               catch ( Exception e ) {
                                                   Log.d( TAG, "down exception " + e.toString() );
                                               }

                                               Log.v( TAG, " new thread" );
                                               new main_thread().start();
                                               new file_thread().start();
                                               new kill_socket().start();
                                           }
                                       }
                                   }

                                 );
    }


    void checkifrunning() {
        DatagramSocket udpSocket = null;

        try {
            FileInputStream reader = openFileInput( "killsocket.txt" );
            String line = "";
            byte[] buffer = new byte[ 10 ];

            char c;

            do {
                reader.read( buffer, 0, 1 );
                c = ( char ) buffer[ 0 ];

                if ( c != '\n' )
                    line += c;
            }
            while ( c != '\n' );

            int port = new Integer( line );

            InetAddress udpaddress = null;

            udpaddress = InetAddress.getByName( "127.0.0.1" );

            byte [] udpmessage = "isalive".getBytes();

            DatagramPacket packet = new DatagramPacket( udpmessage, udpmessage.length, udpaddress, port );

            udpSocket = new DatagramSocket();

            udpSocket.setSoTimeout( 2000 );

            udpSocket.send( packet );

            udpSocket.receive( packet );

            udpSocket.close();

            isrunning = true;
        }
        catch ( Exception e ) {
            isrunning = false;
            Log.d( TAG, "it is false" );
        }

        try {
            udpSocket.close();
        }
        catch ( Exception e ) {}

    }
    //mhayter
    /*
    public class CopyFile extends Thread {
        String mSrc;
        String mDet;
        CopyFile( String Filename1 ) {
            mSrc = Filename1;
            mDet = "UMLogger.txt";
        }

        public void run() {
            try {
                File root = Environment.getExternalStorageDirectory();

                if ( root.canWrite() ) {
                    File logfile = new File( root, mDet );
                    FileOutputStream out = new FileOutputStream( logfile );
                    FileInputStream fin = new FileInputStream( mSrc );
                    byte[] buf = new byte[ 1024 ];
                    int len;

                    while ( ( len = fin.read( buf ) ) > 0 ) {
                        out.write( buf, 0, len );
                        Log.v( "check", "length is " + len );

                    }

                    fin.close();
                    out.close();
                }
            }
            catch ( IOException e ) {
                Log.e( "check", "Could not write file " + e.getMessage() );
            }

        }
    }
	*/
    
    //mhayter
    /*
    class write_to_file extends Thread {
        public void run() {
            String state = Environment.getExternalStorageState();

            if ( state.equalsIgnoreCase( Environment.MEDIA_MOUNTED ) ) {
                try {
                    Log.v( "check", "writing" );
                    String src = "/data/data/eecs.umich.threegtest/files/UMLogger.txt";
                    FileInputStream fin = new FileInputStream( src );
                    fin.close();
                    new CopyFile( src ).start();
                }
                catch ( IOException e ) {
                    // TODO Auto-gen+erated catch block
                    Log.v( "check", "error " + e.getMessage() );
                    e.printStackTrace();
                }
            }
            else {}

        }

    }
	*/
    void config_file_check() {
        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
outer: {
            String line = "";

            try {
                FileInputStream reader = null;

                reader = openFileInput( "config.txt" );

                if ( reader.available() == 0 ) {
                    reader.close();
                    FileOutputStream fOut = null;
                    OutputStreamWriter out = null;
                    // PrintWriter out = null;
                    fOut = openFileOutput( "config.txt", MODE_WORLD_READABLE );
                    out = new OutputStreamWriter( fOut );
                    out.write( "VERSION:2" + "\n" );
                    out.write( "LANDMARK:168.143.162.68,208.80.152.2,74.200.243.254,204.58.233.97,204.155.175.116,69.192.18.125,64.114.206.23,74.86.111.11,66.28.86.67,216.128.7.153,161.58.199.132,199.48.6.72,216.148.129.3,74.125.95.147,139.72.40.50,198.148.166.1,208.73.210.81,137.201.240.50,169.153.202.100,65.182.192.141,206.83.161.134" + "\n" );
                    out.close();
                    fOut.close();
                    break outer;

                }
                else {
                    byte[] buffer = new byte[ 1000 ];
                    char c;

                    do {
                        reader.read( buffer, 0, 1 );
                        c = ( char ) buffer[ 0 ];

                        if ( c != '\n' )
                            line += c;
                    }
                    while ( c != '\n' );

                    reader.close();
                }
            }
            catch ( Exception e ) {
                //TODO Auto-generated catch block
                FileOutputStream fOut = null;
                OutputStreamWriter out = null;
                // PrintWriter out = null;

                try {
                    fOut = openFileOutput( "config.txt", MODE_APPEND );
                    out = new OutputStreamWriter( fOut );
                    out.write( "VERSION:2" + "\n" );
                    out.write( "LANDMARK:168.143.162.68,208.80.152.2,74.200.243.254,204.58.233.97,204.155.175.116,69.192.18.125,64.114.206.23,74.86.111.11,66.28.86.67,216.128.7.153,161.58.199.132,199.48.6.72,216.148.129.3,74.125.95.147,139.72.40.50,198.148.166.1,208.73.210.81,137.201.240.50,169.153.202.100,65.182.192.141,206.83.161.134" + "\n" );
                    out.close();
                    fOut.close();
                }
                catch ( Exception e1 ) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    Log.v( TAG, "got exceptionnn " + e.toString() );

                }

                Log.v( TAG, "got exception " + e.toString() );

                break outer;
            }

            try {
                tcpSocket = new Socket();
                SocketAddress remoteAddr = new InetSocketAddress( serverIP, 3000 );
                tcpSocket.connect( remoteAddr, 4000 );
                os = new DataOutputStream( tcpSocket.getOutputStream() );
                is = new DataInputStream( tcpSocket.getInputStream() );
                tcpSocket.setSoTimeout( 2000 );
                tcpSocket.setTcpNoDelay( true );
            }
            catch ( UnknownHostException e ) {
                //TODO
                Log.v( TAG, "http_caching: cannot resolve tcp host " );
                ncachingcomplete++;
                break outer;
            }
            catch ( Exception e ) {
                //TODO
                Log.v( TAG, "http_caching: cannot get the I/O for tcp connection " );
                ncachingcomplete++;
                break outer;
            }

            if ( tcpSocket == null || os == null || is == null ) {
                //TODO
                Log.v( TAG, "http_caching: tckpSocket or os or is null " );
                ncachingcomplete++;
                break outer;
            }

inner: {

                byte[] message = line.getBytes();

                try {
                    byte[] buffer = new byte[ 10000 ];
                    int read_bytes = 0;
                    os.write( message );
                    read_bytes = is.read( buffer, 0, 10000 );

                    if ( read_bytes <= 0 )
                        break inner;

                    String reply = new String( buffer, 0, read_bytes );

                    if ( reply.equals( "UP-TO-DATE" ) ) {
                        Log.v( TAG, "up to date" );
                    }
                    else {
                        reply += "\n";
                        FileOutputStream fOut = null;
                        OutputStreamWriter out = null;
                        fOut = openFileOutput( "config.txt", MODE_WORLD_READABLE );
                        out = new OutputStreamWriter( fOut );
                        out.write( reply );
                        read_bytes = is.read( buffer, 0, 10000 );

                        if ( read_bytes <= 0 )
                            break inner;

                        reply = new String( buffer, 0, read_bytes );

                        reply += "\n";

                        out.write( reply );

                        out.close();

                    }


                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    Log.v( TAG, "http_caching: error sending data up " + e.getMessage() );
                    break inner;
                }
            }

            try {
                tcpSocket.close();
                os.close();
                is.close();
            }
            catch ( Exception e2 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "http_caching: error closing tcp socket" );
                break outer;
            }
        }

        Log.v( TAG, "came here" );

        try {
            FileInputStream reader = null;
            reader = openFileInput( "config.txt" );
            Log.v( TAG, "avail is " + reader.available() );
            byte[] buffer = new byte[ 1000 ];
            char c;

            do {
                reader.read( buffer, 0, 1 );
                c = ( char ) buffer[ 0 ];

                if ( c != '\n' )
                    line += c;
            }
            while ( c != '\n' );

            Log.v( TAG, "line s " + line );

            line = "";

            do {
                reader.read( buffer, 0, 1 );
                c = ( char ) buffer[ 0 ];

                if ( c != '\n' )
                    line += c;
            }
            while ( c != '\n' );

            Log.v( TAG, "line s " + line );

            reader.close();
        }
        catch ( Exception e ) {
            //TODO Auto-generated catch block
        }

        int index = line.indexOf( ":" );
        int i = 1;
        char c;
        nlandmarkservers = 0;

        do {
            landmarkservers[ nlandmarkservers ] = "";

            do {
                c = line.charAt( index + i );

                if ( c != ',' && c != '\n' )
                    landmarkservers[ nlandmarkservers ] += c;

                i++;
            }
            while ( c != ',' && ( index + i ) < line.length() );

            Log.v( TAG, " " + landmarkservers[ nlandmarkservers ] );

            nlandmarkservers++;

            if ( ( index + i ) >= line.length() )
                break;
        }
        while ( true );

        return ;
    }

    boolean checkstop() {
        if ( stopflag == true ) {
            mProgressStatus = 0;

            try {
                RtcpSocket.close();
                Ros.close();
                Ris.close();
            }
            catch ( Exception e2 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "MAIN: error closing control socket" );
            }

            return true;
        }

        return false;
    }

    void sendudpmessage( String filename, String message ) {
        try {
            FileInputStream reader = openFileInput( filename );
            String line = "";
            byte[] buffer = new byte[ 10 ];

            char c;

            do {
                reader.read( buffer, 0, 1 );
                c = ( char ) buffer[ 0 ];

                if ( c != '\n' )
                    line += c;
            }
            while ( c != '\n' );

            int port = new Integer( line );

            InetAddress udpaddress = null;

            udpaddress = InetAddress.getByName( "127.0.0.1" );

            byte [] udpmessage = message.getBytes();

            DatagramPacket packet = new DatagramPacket( udpmessage, udpmessage.length, udpaddress, port );

            DatagramSocket udpSocket = null;

            udpSocket = new DatagramSocket();

            udpSocket.setSoTimeout( 4000 );

            udpSocket.send( packet );

            udpSocket.close();
        }
    catch ( Exception e ) {}

    }

    long getrepeattime() {
        try {
            FileInputStream reader = openFileInput( "repeatfile.txt" );
            String line = "";
            byte[] buffer = new byte[ 10 ];

            char c;

            do {
                reader.read( buffer, 0, 1 );
                c = ( char ) buffer[ 0 ];

                if ( c != '\n' )
                    line += c;
            }
            while ( c != '\n' );

            long port = new Long( line );

            reader.close();

            return port;
        }
    catch ( Exception e ) {}

        return -1;
    }

    class kill_socket extends Thread {
        public void run() {
            this.setPriority( MAX_PRIORITY );

            try {
                DatagramSocket killSocket = new DatagramSocket();
                Log.v( TAG, "bound to  " + killSocket.getLocalPort() );

                try {
                    FileOutputStream fOut1 = null;
                    OutputStreamWriter out1 = null;
                    fOut1 = openFileOutput( "killsocket.txt", MODE_WORLD_READABLE );
                    out1 = new OutputStreamWriter( fOut1 );
                    out1.write( "" + killSocket.getLocalPort() + "\n" );
                    out1.close();
                    fOut1.close();
                }
                catch ( Exception e ) {
                    Log.d( TAG, "down exception " + e.toString() );
                }

                killSocket.setReuseAddress( true );

                do {
                    byte[] recvbuf = new byte[ 1024 ];
                    DatagramPacket rpacket = new DatagramPacket( recvbuf, recvbuf.length );
                    Log.d( TAG, "watng to recv" );
                    killSocket.receive( rpacket );
                    String reply = new String( rpacket.getData(), rpacket.getData().length );

                    if ( reply.charAt( 0 ) == 'k' ) {
                        stopflag = true;
                        killSocket.close();
                        return ;
                    }
                    else if ( reply.charAt( 0 ) == 'i' ) {
                        try {
                            FileOutputStream fOut1 = null;
                            OutputStreamWriter out1 = null;
                            fOut1 = openFileOutput( "uiportfile.txt", MODE_WORLD_READABLE );
                            out1 = new OutputStreamWriter( fOut1 );
                            out1.write( "" + rpacket.getPort() + "\n" );
                            out1.close();
                            fOut1.close();
                        }
                        catch ( Exception e ) {}

                        sendudpmessage( "uiportfile.txt", "yes" );
                    }
                }
                while ( true );
            }
            catch ( Exception e ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "in kill exception " + e.toString() );
                e.printStackTrace();
            }

        }
    }

    FileOutputStream fOut = null;
    OutputStreamWriter out = null;
    long version;



    class main_thread extends Thread {
        public void run() {
            PowerManager pm = ( PowerManager ) getSystemService( Context.POWER_SERVICE );
            PowerManager.WakeLock wl;
            wl = pm.newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, "My Tag" );
            WifiManager wm = ( WifiManager ) getSystemService( Context.WIFI_SERVICE );
            WifiManager.WifiLock wlw = wm.createWifiLock( "yes TAG" );
            //deviceID = wm.getConnectionInfo().getMacAddress();
            stopflag = false;
            long repeattime = -1;


            this.setPriority( MAX_PRIORITY );
            int roundrunning = 0;
            version = time();
            long gotversion = 0;

            try {
                FileOutputStream fOut1 = null;
                OutputStreamWriter out1 = null;
                fOut1 = openFileOutput( "versionfile.txt", MODE_WORLD_READABLE );
                out1 = new OutputStreamWriter( fOut1 );
                out1.write( "" + version + "\n" );
                out1.close();
                fOut1.close();
            }
            catch ( Exception e ) {
                Log.d( TAG, "down exception " + e.toString() );
            }

            do {
                wl.acquire();
                wlw.acquire();

                try {
                    FileInputStream reader = openFileInput( "versionfile.txt" );
                    String line = "";
                    byte[] buffer = new byte[ 10 ];

                    char c;

                    do {
                        reader.read( buffer, 0, 1 );
                        c = ( char ) buffer[ 0 ];

                        if ( c != '\n' )
                            line += c;
                    }
                    while ( c != '\n' );

                    gotversion = new Long( line );
                }
            catch ( Exception e ) {}

                if ( gotversion != version )
                    return ;

                Log.d( TAG, "incrementing roundrunning" );

                roundrunning++;

                try {
                    FileOutputStream fOut1 = null;
                    OutputStreamWriter out1 = null;
                    fOut1 = openFileOutput( "roundfile.txt", MODE_WORLD_READABLE );
                    out1 = new OutputStreamWriter( fOut1 );
                    out1.write( "" + roundrunning + "\n" );
                    out1.close();
                    fOut1.close();
                }
                catch ( Exception e ) {
                    Log.d( TAG, "down exception " + e.toString() );
                }

                inflag = true;


                pingflag = true;

                if ( checkstop() ) {
                    stopflag = false;
                    wl.release();
                    wlw.release();
                    return ;
                }

                mHandler.post( new Runnable() {
                                   public void run() {
                                       imps = 1;
                                       mProgress.setProgress( imps );
                                       t2.setText( "" + 1 + "% Complete" );
                                       hdoneflag = true;
                                   }
                               }

                             );
                mProgressStatus = 1;
                completed = 0;
                bit = 0;
                
                serverIP = "141.212.111.182";

                if ( pingS( serverIP, 5, 1, 0, 3000 ) == -1 ) {
                    serverIP = ALTERNATIVE_IP;
                    //if(pingS("www.google.com",5,1,0,3000)==-1)
                    
                    //mhayter
                    tester.setNetworkStatus(false);
                    //network_status = false;
                    //serverIP = "141.212.111.182";


                }
                else {
                	//mhayter
                	tester.setNetworkStatus(true);
                    //network_status = true;
                }
                
                //mhayter
                if ( tester.getNetworkStatus() == false ) {
                    pingflag = false;
                    Socket tcpSocket = null;

                    try {
                        tcpSocket = new Socket();
                        SocketAddress remoteAddr = new InetSocketAddress( httpserverIP, 80 );
                        tcpSocket.connect( remoteAddr, 2000 );
                        tcpSocket.setSoTimeout( 2000 );
                        tcpSocket.setTcpNoDelay( true );
                    }
                    catch ( Exception e ) {
                        //TODO
                    }

                    if ( tcpSocket != null ) {
                    	//mhayter
                    	tester.setNetworkStatus(true);
                        //network_status = true;

                    }

                    try {
                        tcpSocket.close();
                    }
                    catch ( Exception e2 ) {}

                }

                Log.d( TAG, "incrementing roundrunning" );

                boolean isEnabled = Settings.System.getInt( context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0 ) == 1;
                Log.v( TAG, " enabled " + isEnabled );

                if ( isEnabled ) {
                	//mhayter
                	tester.setNetworkStatus(false);
                    //network_status = false;
                }
                
                //mhayter
                if ( tester.getNetworkStatus() == true ) {
                    long fullstart, fullend;
                    fullstart = time();




                    long endt, strt;
                    strt = time();
                    long totaltime = 0;
                    Info();

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    Rflag = false;
                    //mhayter
                    prefix = "<Gphone><" + tester.getDeviceID() + "><" + runID + ">";
                    //prefix = "<Gphone><" + deviceID + "><" + runID + ">";
                    //sendReport(serverIP,prefix);
                    Log.v( "check", prefix );
                    Log.v( TAG, "got info" );

                    sendReport( serverIP, infoS );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }
                    //mhayter
                    netinfoS = "NETWORK:" + "<Carrier:" + tester.getNetworkOperator() + "><Type:";
                    //netinfoS = "NETWORK:" + "<Carrier:" + networkOperator + "><Type:";
                    Log.v( TAG, " info is " + infoS );






                    // Update the progress bar

                    mProgressStatus = 2;
                    //mhayter
                    message = "NetworkType: ";
                    String tempNetworkType = "";
                    if (tester.getNetworkTypeName().equals("MOBILE"))
                    	tempNetworkType = tester.getMobileNetworkTypeName();
                    else
                    	tempNetworkType = "WIFI";
                    message += tempNetworkType;
                    netinfoS += tempNetworkType;
                    
                    //mhayter
                    /*
                    if ( wifi_or_3G == 1 ) {
                        message = "NetworkType: WIFI";
                        netinfoS += "WIFI";
                    }
                    else {
                        if ( networktype == 2 ) {
                            message = "NetworkType: EDGE";
                            netinfoS += "EDGE";
                        }
                        else if ( networktype == 3 ) {
                            message = "NetworkType: UMTS";
                            netinfoS += "UMTS";
                        }
                        else if ( networktype == 1 ) {
                            message = "NetworkType: GPRS";
                            netinfoS += "EDGE";
                        }
                        else {
                            message = "NetworkType: MOBILE";
                            netinfoS += "MOBILE";
                        }
                    }
					*/
                    try {
                        fOut = openFileOutput( filename, MODE_WORLD_READABLE );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_WORLD_READABLE );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );

                    }
                    catch ( IOException e ) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    message = "GPS location: " + lat + "N, " + longt + "W";

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( IOException e ) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    netinfoS += ">;";
                    sendReport( serverIP, netinfoS );
                    random_dns();

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }


                    endt = time();
                    Log.d( TAG, "RUNtime " + ( endt - strt ) );
                    totaltime += ( endt - strt );
                    strt = time();

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    //local ip vs global ip
                    replycode = HttpNatExistence( serverIP );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "ADDRESS:";
                    result += "<LocalIp:" + localip + ">:<GloblalIp:" + seenip + ">;";

                    if ( replycode >= 7 ) {
                        message = "Local IP address: " + localip;
                        message1 = "Global IP address: " + seenip;
                    }
                    else {
                        message = "Local IP address: Error in test";
                        message1 = "Global IP address: Error in test";
                    }

                    mProgressStatus = 3;

                    try {
                    	//Open output stream writer for "filename" in append mode
                    	/*
                    	 	write :
                    	    " 
                    	 	message\n
                    		mProgressStatus\n
                    		message1\n
                    		mProgressStatus\n
                    		"
                    	*/
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                        
                        out.write( "" + message1 + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        
                        //Open output stream writer for "filename1" in append mode
                    	/*
                    	 	write :
                    	    " 
                    	 	message\n
                    	 	message1\n
                    		"
                    	*/
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        
                        out.write( message + "\n" );
                        out.write( message1 + "\n" );
                        
                        out.close();
                        fOut.close();
                        
                        //why are out and fOut closed again?
                        sendudpmessage( "uiprint.txt", "" + message1.length() + "!" + message1 + "" + mProgressStatus + "!" );
                        out.close();
                        fOut.close();
                    }
                    catch ( Exception e ) {}

                    Log.v( TAG, result );

                    result += "\n";
                    sendReport( serverIP, result );
                    // Update the progress bar
                    /*  mHandler.post(new Runnable() {
                          public void run() {
                    mProgressStatus = 3;
                           mProgress.setProgress(mProgressStatus);
                           t2.setText(""+mProgressStatus+"% Complete");
                           t3.setText("Running test 3/13");
                        adapter.add(message);
                        lvw.setAdapter(adapter);
                        adapter.add(message1);
                       lvw.setAdapter(adapter);
                          }
                      });*/
                    endt = time();
                    Log.d( TAG, "RUNtime " + ( endt - strt ) );
                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    // DNS request google
                    replycode = DNSReqGoogle();

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    if ( DNSGOOGLE == true ) {
                        message = "Local DNS server status: UP";
                    }
                    else {
                        message = "Local DNS server status: DOWN";
                    }

                    mProgressStatus = 4;

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();

                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                        public void run() {
                    mProgressStatus = 4;
                         mProgress.setProgress(mProgressStatus);
                         t2.setText(""+mProgressStatus+"% Complete");
                          t3.setText("Running test 4/13");
                       adapter.add(message);
                           lvw.setAdapter(adapter);
                        }
                    });   */

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    // popular domains
                    thread1doneflag = false;
                    thread2doneflag = false;
                    config_file_check();

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    new thread1().start();
                    new thread2().start();

                    do {

                        try {
                            Thread.sleep( 2000 );
                        }
                        catch ( InterruptedException e ) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    while ( thread1doneflag == false || thread2doneflag == false );

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    result = "DNS:";
                    // DNS UMICH
                    replycode = DNS_UMICH( umichserverIP1 );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    DNSUMICH = true;

                    if ( DNSUMICH == true ) {
                        message = "DNS lookup to external server allowed?: Yes";
                        result += "<DnsToExternalServerAllowed: Yes>";
                    }
                    else if ( replycode == 6 ) {
                        message = "DNS lookup to external server allowed?: No";
                        result += "<DnsToExternalServerAllowed: No>";
                    }
                    else if ( replycode == 4 ) {
                        message = "DNS lookup to external server allowed?: No";
                        result += "<DnsToExternalServerAllowed: No>";
                    }
                    else {
                        message = "DNS lookup to external server allowed?: Error in test";
                        result += "<DnsToExternalServerAllowed: Error in test>";
                    }

                    mProgressStatus = 46;

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                     public void run() {
                    mProgressStatus = 46;
                      mProgress.setProgress(mProgressStatus);
                      t2.setText(""+mProgressStatus+"% Complete");
                           t3.setText("Running test 7/13");
                      adapter.add(message);
                           lvw.setAdapter(adapter);
                     }
                    });*/

                    result += ";";

                    Log.v( TAG, result );

                    result += "\n";

                    sendReport( serverIP, result );

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    //signal

                    if ( pingflag ) {
                        lat_2ndhop();

                        if ( checkstop() ) {
                            stopflag = false;
                            wl.release();
                            wlw.release();
                            return ;
                        }

                        message = "Signal strength level from 0 (low) to 10 (high): " + ( 10 - lossrateservers[ 0 ] );

                        if ( 10 - lossrateservers[ 0 ] > 8 )
                            message += " Good";
                        else if ( 10 - lossrateservers[ 0 ] > 5 )
                            message += " Moderate";
                        else
                            message += " Bad";
                    }
                    else {
                        message = "Signal strength level from 0 (low) to 10 (high): Cannot run test, your provider blocks outgoing Ping Packets";
                    }

                    mProgressStatus = 48;

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( IOException e1 ) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    /* mHandler.post(new Runnable() {
                      public void run() {
                    mProgressStatus = 48;
                       mProgress.setProgress(mProgressStatus);
                       t2.setText(""+mProgressStatus+"% Complete");
                            t3.setText("Running test 8/13");
                       adapter.add(message);
                          lvw.setAdapter(adapter);
                      }
                     });*/
                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }




                    // caching tests

                    strt = time();

                    replycode = http_caching();

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "HTTP:";

                    if ( replycode != 12 ) {
                        message = "HTTP caching detection: Error in test";
                        result += "<Cache: Error>:";
                    }
                    else {
                        if ( cachflag == true ) {
                            message = "HTTP caching detection: Detected";
                            result += "<Cache: Yes>:";
                        }
                        else {
                            message = "Http Caching detection: Not detected";
                            result += "<Cache: No>:";
                        }
                    }

                    Log.v( TAG, result );
                    mProgressStatus = 50;
                    /*try {
                     fOut = openFileOutput(filename,MODE_APPEND);
                           out = new OutputStreamWriter(fOut);  
                    out.write(message+"\n");
                    out.write(""+mProgressStatus+"\n");
                    out.close();
                    fOut.close();
                    fOut = openFileOutput(filename1,MODE_APPEND);
                    out = new OutputStreamWriter(fOut);  
                    out.write(message+"\n");
                    out.close();
                    fOut.close();
                    sendudpmessage("uiprint.txt",""+message.length()+"!"+message+""+mProgressStatus+"!");
                    traceroute1();
                    } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    }*/ 
                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                     public void run() {
                      
                      adapter.add(message);
                           lvw.setAdapter(adapter);
                     }
                    });*/
                    endt = time();
                    Log.d( TAG, "RUNtime " + ( endt - strt ) );
                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();

                    if ( replycode != 12 ) {
                        message = "Http Proxy detection: Error in test";
                        result += "<Compression: Error>;";
                    }
                    else {
                        if ( compressionflag == true ) {
                            message = "Http Proxy detection: Detected";
                            result += "<Compression: Yes>;";
                        }
                        else {
                            message = "Http Proxy detection: Not detected";
                            result += "<Compression: No>;";
                        }
                    }

                    Log.v( TAG, result );
                    result += "\n";
                    sendReport( serverIP, result );
                    mProgressStatus = 50;
                    /*try {
                    fOut = openFileOutput(filename,MODE_APPEND);
                       out = new OutputStreamWriter(fOut);  
                    out.write(message+"\n");
                    out.write(""+mProgressStatus+"\n");
                    out.close();
                    fOut.close();
                    fOut = openFileOutput(filename1,MODE_APPEND);
                    out = new OutputStreamWriter(fOut);  
                    out.write(message+"\n");
                    out.close();
                    fOut.close();
                    sendudpmessage("uiprint.txt",""+message.length()+"!"+message+""+mProgressStatus+"!");
                    } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    }
                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                    public void run() {
                    mProgressStatus = 50;
                     mProgress.setProgress(mProgressStatus);
                     t2.setText(""+mProgressStatus+"% Complete");
                     t3.setText("Running test 9/13");
                     adapter.add(message);
                          lvw.setAdapter(adapter);
                    }
                    });*/ 
                    // bit torrent differentiation

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    //// random bit torrent
                    replycode = BTptosUp( serverIP, PORT_BT_RAND );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "BT:";

                    if ( btblockedstage.equals( "E" ) ) {
                        message = "BitTorrent uplink traffic: No blocking ";
                        result += "<NondftUpBlockedStage: NONE>;";
                    }
                    else if ( btblockedstage.equals( "S" ) ) {
                        message = "BitTorrent uplink traffic: Error in test";
                        result += "<NondftUpBlockedStage: Error>;";
                    }
                    else {
                        message = "BitTorrent uplink traffic: Blocked ";
                        result += "<NondftUpBlockedStage: " + btblockedstage + ">;";
                    }

                    Log.v( TAG, " " + result );
                    result += "\n";
                    sendReport( serverIP, result );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }


                    replycode = BTptosUp( serverIP, PORT_BT );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "BT:";

                    if ( btblockedstage.equals( "E" ) ) {
                        message = "BitTorrent uplink traffic: No blocking ";
                        result += "<DftUpBlockedStage: None>;";
                    }
                    else if ( btblockedstage.equals( "S" ) ) {
                        message = "BitTorrent uplink traffic: Error in test";
                        result += "<DftUpBlockedStage: Error>;";
                    }
                    else {
                        message = "BitTorrent uplink traffic: Blocked ";
                        result += "<DftUpBlockedStage: " + btblockedstage + ">;";
                    }

                    mProgressStatus = 61;


                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );

                        if ( destinationreached == false )
                            traceroute2();
                    }
                catch ( Exception e ) {}

                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                     public void run() {
                    mProgressStatus = 61;
                      mProgress.setProgress(mProgressStatus);
                      t2.setText(""+mProgressStatus+"% Complete");
                      adapter.add(message);
                           t3.setText("Running test 10/13");
                           lvw.setAdapter(adapter);          
                     }
                    });*/

                    Log.v( TAG, " " + result );

                    result += "\n";

                    sendReport( serverIP, result );

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();


                    replycode = BTptosDown( serverIP, PORT_BT_RAND );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "BT:";

                    if ( btblockedstage.equals( "E" ) ) {
                        message = "BitTorrent downlink traffic: No blocking ";
                        result += "<NondftDownBlockedStage: None>;";
                    }
                    else if ( btblockedstage.equals( "S" ) ) {
                        message = "BitTorrent downlink traffic: Error in test";
                        result += "<NondftDownBlockedStage: Error>;";
                    }
                    else {
                        message = "BitTorrent downlink traffic: Blocked at " + btblockedstage;
                        result += "<NondftDownBlockedStage: " + btblockedstage + ">;";
                    }



                    Log.v( TAG, " " + result );
                    result += "\n";
                    sendReport( serverIP, result );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "BT:";

                    replycode = BTptosDown( serverIP, PORT_BT );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    if ( btblockedstage.equals( "E" ) ) {
                        message = "BitTorrent downlink traffic: No blocking ";
                        result += "<DftDownBlockedStage: None>;";
                    }
                    else if ( btblockedstage.equals( "S" ) ) {
                        message = "BitTorrent downlink traffic: Error in test";
                        result += "<DftDownBlockedStage: Error>;";
                    }
                    else {
                        message = "BitTorrent downlink traffic: Blocked ";
                        result += "<DftDownBlockedStage: " + btblockedstage + ">;";
                    }

                    mProgressStatus = 73;

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );

                        if ( destinationreached == false )
                            traceroute3();
                    }
                catch ( Exception e ) {}

                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                     public void run() {
                    mProgressStatus = 73;
                      mProgress.setProgress(mProgressStatus);
                      t2.setText(""+mProgressStatus+"% Complete");
                           t3.setText("Running test 11/13");
                      adapter.add(message);
                           lvw.setAdapter(adapter);          
                     }
                    });*/
                    Log.v( TAG, " " + result );

                    result += "\n";

                    sendReport( serverIP, result );

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    /// random


                    replycode = BTRandom( serverIP );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "BT:";

                    if ( replycode < 5 ) {
                        result += "<RandomBlockedStage: SYN>;";
                    }
                    else if ( replycode < 10 ) {
                        result += "<RandomBlockedStage: Transfer>;";
                    }
                    else {
                        result += "<RandomBlockedStage: None>;";
                    }

                    Log.v( TAG, " " + result );
                    result += "\n";
                    sendReport( serverIP, result );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    replycode = HTTPptosUp( serverIP );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    /*mHandler.post(new Runnable() {
                     public void run() {
                    mProgressStatus = 80;
                      mProgress.setProgress(mProgressStatus);
                      t2.setText(""+mProgressStatus+"% Complete");
                     }
                    });*/

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    replycode = HTTPptosDown( serverIP );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    // Reachability
                    reachi = 0;
                    rports = 0;

                    for ( int j = 0;j < ports.length;j++ ) {
                        if ( checkstop() ) {
                            stopflag = false;
                            wl.release();
                            wlw.release();
                            return ;
                        }

                        new Reachability( j ).start();
                        reachi ++;
                    }

                    do {
                        if ( checkstop() ) {
                            stopflag = false;
                            wl.release();
                            wlw.release();
                            return ;
                        }

                        try {
                            Thread.sleep( 2000 );
                        }
                        catch ( InterruptedException e ) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    while ( rports < ports.length );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    message = "";
                    result = "REA";
                    message = "Blocked ports for direct access: ";
                    message1 = "Allowed ports for direct access: ";

                    if ( true ) {
                        int blocked = 0;

                        for ( int i = 0;i < REACHB.length;i++ ) {
                            result += ":";

                            if ( REACHB[ i ] == false ) {
                                message += ports[ i ] + " (" + portnames[ i ] + ")" + " ";
                                Log.v( TAG, " REACHBst " + REACHBst[ i ] );

                                if ( REACHBst[ i ] == 'c' )
                                    result += "<" + ports[ i ] + ": CONNECT>";
                                else
                                    result += "<" + ports[ i ] + ": RECV>";
                            }
                            else {
                                message1 += ports[ i ] + " (" + portnames[ i ] + ")" + " ";
                                result += "<" + ports[ i ] + ": OK>";
                            }
                        }

                    }

                    mProgressStatus = 88;

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                        out.write( message1 + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( message1 + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message1.length() + "!" + message1 + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                    // Update the progress bar
                    /* mHandler.post(new Runnable() {
                      public void run() {
                    mProgressStatus = 88;
                       mProgress.setProgress(mProgressStatus);
                       t2.setText(""+mProgressStatus+"% Complete");
                            t3.setText("Running test 12/13");
                       adapter.add(message);
                            lvw.setAdapter(adapter);
                      }
                     });*/
                    result += ";";

                    Log.v( TAG, result );

                    result += "\n";

                    sendReport( serverIP, result );

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );

                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();

                    // downlink tput
                    replycode = MeasureDownlinkTput( serverIP );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "DOWN:";

                    if ( replycode == 7 ) {
                        message = "TCP downlink bandwidth (kbps): " + ( ( downlinksize / downlinktime ) * ( 1000 / 128 ) );
                        result += "<Tp: " + ( ( downlinksize / downlinktime ) * ( 1000 / 128 ) ) + ">";

                        if ( ( ( downlinksize / downlinktime ) * ( 1000 / 128 ) ) > 500 )
                            message += " Good";
                        else if ( ( ( downlinksize / downlinktime ) * ( 1000 / 128 ) ) > 130 )
                            message += " Moderate";
                        else
                            message += " Bad";
                    }
                    else {
                        message = "TCP downlink bandwidth (kbps): Network problem in test";
                        result += "<Tp :Network problem in test>";
                    }

                    mProgressStatus = 94;

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );

                        if ( destinationreached == false )
                            traceroute4();
                    }
                catch ( Exception e ) {}

                    result += ";";

                    Log.v( TAG, result );
                    result += "\n";
                    sendReport( serverIP, result );


                    // Update the progress bar
                    /*mHandler.post(new Runnable() {
                     public void run() {
                    mProgressStatus = 94;
                      mProgress.setProgress(mProgressStatus);
                      t2.setText(""+mProgressStatus+"% Complete");
                           t3.setText("Running test 13/13");
                      adapter.add(message);
                           lvw.setAdapter(adapter);
                     }
                     });*/ 
                    // uplink tput
                    endt = time();
                    Log.d( TAG, "RUNtime " + ( endt - strt ) );
                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    strt = time();
                    replycode = MeasureUplinkTput( serverIP );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    result = "UP:";

                    if ( replycode == 7 ) {
                        message = "TCP uplink bandwidth (kbps): " + ( uplinksize / ( 128 * 60 ) );
                        result += "<Tp: " + ( uplinksize / ( 128 * 60 ) ) + ">";

                        if ( ( uplinksize / ( 128 * 60 ) ) > 100 )
                            message += " Good";
                        else if ( ( uplinksize / ( 128 * 60 ) ) > 30 )
                            message += " Moderate";
                        else
                            message += " Bad";
                    }
                    else {
                        message = "TCP uplink bandwidth (kbps): Network problem in test";
                        result += "<Tp: Network prolem in test>";
                    }

                    mProgressStatus = 100;
                    result += ";";
                    Log.v( TAG, result );
                    result += "\n";
                    sendReport( serverIP, result );

                    try {
                        RtcpSocket.close();
                        Ros.close();
                        Ris.close();
                    }
                    catch ( Exception e2 ) {
                        // TODO Auto-generated catch block
                        Log.v( TAG, "MAIN: error closing control socket" );
                    }

                    try {
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                    endt = time();

                    Log.d( TAG, "RUNtime " + ( endt - strt ) );
                    totaltime += ( endt - strt );

                    if ( checkstop() ) {
                        stopflag = false;
                        wl.release();
                        wlw.release();
                        return ;
                    }

                    fullend = time();
                    Log.d( TAG, "Total run time " + ( fullend - fullstart ) );

                }
                else {
                    mProgressStatus = 100;
                    message = "Network down or your provider blocks ICMP Ping";

                    try {
                        fOut = openFileOutput( filename, MODE_WORLD_READABLE );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_WORLD_READABLE );
                        out = new OutputStreamWriter( fOut );
                        out.write( message + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                }

                mProgressStatus = 100;

                // Update the progress bar

                new write_to_file().start();

                try {
                    Thread.sleep( 2000 );
                }
                catch ( InterruptedException e ) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                completed = 1;
                bit = 0;
                wl.release();
                wlw.release();


            }
            while ( repeattime != -1 );

            sendudpmessage( "uiprint.txt", "1001!" );

            sendudpmessage( "killsocket.txt", "kill" );

            hdoneflag2 = false;

            mHandler.post( new Runnable() {
                               public void run() {
                                   t3.setText( "Run complete, press button to restart app" );
                                   hdoneflag2 = true;
                               }
                           }

                         );

            while ( hdoneflag2 == false ) {}

            return ;
        }

    }

    boolean hdoneflag2;
    // sending data
    int sendReport( String serverIP, String result ) {
        result += "\n";
        Rflag = false;

        if ( Rflag == false ) {
            try {
                RtcpSocket = new Socket();
                SocketAddress remoteAddr = new InetSocketAddress( serverIP, PORT_CONTROL );
                RtcpSocket.connect( remoteAddr, 2000 );
                Ros = new DataOutputStream( RtcpSocket.getOutputStream() );
                Ris = new DataInputStream( RtcpSocket.getInputStream() );
                RtcpSocket.setSoTimeout( 4000 );
            }
            catch ( UnknownHostException e ) {
                // TODO
                Log.v( TAG, "sendReport: cannot resolve host" );
                return 2;
            }
            catch ( Exception e ) {
                //TODO
                Log.v( TAG, "sendReport: cannot get the I/O for connection" );
                return 3;
            }

            if ( RtcpSocket == null || Ros == null || Ris == null ) {
                //TODO
                Log.v( TAG, "sendReport: tckpSocket or os or is null" );
                return 4;
            }

            Rflag = true;
        }

        byte [] message = result.getBytes();
        Log.v( "PR", "result is " + result );

        try {
            byte[] buffer = new byte[ 1000 ];
            int read_bytes;
            byte [] message1 = prefix.getBytes();

            Ros.write( message1 );
            Thread.sleep( 1000 );
            read_bytes = Ris.read( buffer, 0, 1000 );

            if ( read_bytes > 0 ) {
                String reply = new String( buffer, 0, read_bytes );
                Log.v( TAG, "reply is " + reply );
            }

        }
        catch ( Exception e ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "sendRepo: error sending result back " + e.getMessage() );
            //return 5;
        }

        try {
            Ros.write( message );
            RtcpSocket.close();
            Ros.close();
            Ris.close();
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "MAIN: error closing control socket" );
        }

        return 6;

    }


    void Info() {
    	//mhayter
        //TelephonyManager mT = ( TelephonyManager ) getSystemService( Context.TELEPHONY_SERVICE );
        runID = time();
        //mhayter
        //deviceID = mT.getDeviceId();
        //mhayter
        //networkOperator = mT.getNetworkOperatorName();
        //networktype = mT.getNetworkType();
        
        //mhayter
        //ConnectivityManager cT = ( ConnectivityManager ) getSystemService( Context.CONNECTIVITY_SERVICE );
        //wifi_or_3G = cT.getActiveNetworkInfo().getType();

        Geocoder gc = new Geocoder( this );
        String zipcode = null;
        String city = null;

        if ( location != null ) {
            try {
                List<Address> address = gc.getFromLocation( lat, longt, 1 );

                if ( address != null ) {
                    zipcode = address.get( 0 ).getPostalCode();
                    city = address.get( 0 ).getLocality();
                }
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        //mhayter
        Log.v( TAG, "id is " + tester.getDeviceID() );
        //Log.v( TAG, "id is " + deviceID );
        
        Log.v( TAG, "id is " + runID );

        //mhayter
        infoS = "DEVICE:<ID:" + tester.getDeviceID() + ">:<TYPE:Gphone>" + ":<RID:" + runID + ">:<ZIPcode:" + zipcode + ">:<City:" + city + ">:<LocationLatitude:" + lat + ">:<LocationLongitude:" + longt + ">;";
        //infoS = "DEVICE:<ID:" + deviceID + ">:<TYPE:Gphone>" + ":<RID:" + runID + ">:<ZIPcode:" + zipcode + ">:<City:" + city + ">:<LocationLatitude:" + lat + ">:<LocationLongitude:" + longt + ">;";

    }

    LocationManager lm = null;
    LocationListener locationListener;

    // location

    void location() {
        lm = ( LocationManager ) getSystemService( Context.LOCATION_SERVICE );
        locationListener = new MyLocationListener();
        List<String> list = lm.getAllProviders();
        String provider = null;
        String provider2 = null;

        for ( int i = 0;i < list.size();i++ ) {

            if ( lm.isProviderEnabled( list.get( i ) ) ) {
                if ( provider == null )
                    provider = list.get( i );
                else
                    provider2 = list.get( i );

                if ( provider != null && provider2 != null )
                    break;
            }
        }

        location = null;

        if ( provider != null )
            lm.requestLocationUpdates( provider, 100, 0, locationListener );

        if ( provider2 != null )
            lm.requestLocationUpdates( provider2, 100, 0, locationListener );


    }

    private class MyLocationListener implements LocationListener {
        public void onLocationChanged( Location loc ) {
            // Called when the location has changed.

            if ( loc != null ) {
                location = loc;
                lat = loc.getLatitude();
                longt = loc.getLongitude();
                Log.v( TAG, "I got location " + loc );
                lm.removeUpdates( locationListener );
            }
        }

        public void onProviderDisabled( String provider ) {
            // TODO Auto-generated method stub

        }

        public void onProviderEnabled( String provider ) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged( String provider, int status, Bundle extras ) {
            // TODO Auto-generated method stub

        }
    }

    InetAddress addr = null;

    int random_dns() {
        long strttime = time();
        mHandler.post( new Runnable() {
                           public void run() {
                               try {
                            	   //mhayter
                            	   String host = "gphone_" + tester.getDeviceID() + "_" + runID + ".eecs.umich.edu";
                                   //String host = "gphone_" + deviceID + "_" + runID + ".eecs.umich.edu";
                                   addr = InetAddress.getByName( host );
                               }
                               catch ( UnknownHostException e ) {}

                           }

                       }

                     );

        long endtime = time();

        while ( endtime - strttime < 2000 && addr == null ) {
            endtime = time();
        }

        String result = null;

        if ( addr == null ) {
        	//mhayter
        	result = "DNS-Unique:<" + "gphone_" + tester.getDeviceID() + "_" + runID + ".eecs.umich.edu" + ":0.00>;";
            //result = "DNS-Unique:<" + "gphone_" + deviceID + "_" + runID + ".eecs.umich.edu" + ":0.00>;";
        }
        else {
        	//mhayter
        	result = "DNS-Unique:<" + "gphone_" + tester.getDeviceID() + "_" + runID + ".eecs.umich.edu" + ":" + ( endtime - strttime ) + ">;";
            //result = "DNS-Unique:<" + "gphone_" + deviceID + "_" + runID + ".eecs.umich.edu" + ":" + ( endtime - strttime ) + ">;";
        }

        Log.v( "check", result );

        sendReport( serverIP, result );

        return 2;
    }

    String tracerouteresult = "TRACEROUTE";

    int traceroute1() {
        destinationreached = false;

        for ( int i = 0;i < 5;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            long k = pingS( serverIP, i + 1, 0, 0, 2000 );

            if ( destinationreached == true ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + serverIP + ":" + k + ">;";
                break;
            }

            if ( k != -1 ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + signalservers + ":" + k + ">";
            }
            else {
                tracerouteresult += ":<" + ( i + 1 ) + "::0.00>";
            }
        }

        if ( destinationreached == true )
            sendReport( serverIP, tracerouteresult );

        return 2;
    }

    int traceroute2() {
        destinationreached = false;

        for ( int i = 5;i < 10;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            long k = pingS( serverIP, i + 1, 0, 0, 2000 );

            if ( destinationreached == true ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + serverIP + ":" + k + ">;";
                break;
            }

            if ( k != -1 ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + signalservers + ":" + k + ">";
            }
            else {
                tracerouteresult += ":<" + ( i + 1 ) + "::0.00>";
            }
        }

        if ( destinationreached == true )
            sendReport( serverIP, tracerouteresult );

        return 2;
    }

    int traceroute3() {
        destinationreached = false;

        for ( int i = 10;i < 15;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            long k = pingS( serverIP, i + 1, 0, 0, 2000 );

            if ( destinationreached == true ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + serverIP + ":" + k + ">;";
                break;
            }

            if ( k != -1 ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + signalservers + ":" + k + ">";
            }
            else {
                tracerouteresult += ":<" + ( i + 1 ) + "::0.00>";
            }
        }

        if ( destinationreached == true )
            sendReport( serverIP, tracerouteresult );

        return 2;
    }

    int traceroute4() {
        destinationreached = false;

        for ( int i = 15;i < 20;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            long k = pingS( serverIP, i + 1, 0, 0, 2000 );

            if ( destinationreached == true ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + serverIP + ":" + k + ">;";
                break;
            }

            if ( k != -1 ) {
                tracerouteresult += ":<" + ( i + 1 ) + ":" + signalservers + ":" + k + ">";
            }
            else {
                tracerouteresult += ":<" + ( i + 1 ) + "::0.00>";
            }
        }

        sendReport( serverIP, tracerouteresult );
        return 2;
    }

    Process p = null;
    String line;
    BufferedReader input;
    int times, tl, sl;
    long starttime;
    String pingserverIP;
    boolean destinationreached = false;
    long pingS( String serverIP, int times_p, int tl_p, int sl_p, long timeout ) {

        times = times_p;
        tl = tl_p;
        sl = sl_p;
        pingserverIP = serverIP;
        line = null;
        boolean flag;

        try {
            long endtime;
            //mHandler.post(new Runnable() {
            //  public void run() {

            if ( tl == 0 ) {
                try {
                    starttime = time();
                    p = Runtime.getRuntime().exec( "ping -c 1 -t " + times + " " + pingserverIP );
                    input = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
                    line = input.readLine();
                }
                catch ( Exception e1 ) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

            if ( tl == 1 ) {
                try {
                    starttime = time();
                    p = Runtime.getRuntime().exec( "ping -c 1 " + pingserverIP );
                    input = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
                    line = input.readLine();
                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            //  }
            //});


            while ( true ) {
                endtime = time();

                while ( endtime - starttime < timeout && line == null ) {
                    endtime = time();
                    line = input.readLine();
                }

                Log.v( TAG, "ping result " + line );

                if ( line == null ) {
                    p.destroy();
                    break;
                }

                line = input.readLine();

                if ( line == null )
                    break;

                long timeforresponse = endtime - starttime;

                if ( line.indexOf( "From" ) != -1 && tl == 0 ) {
                    if ( tl == 0 ) {
                        int i = line.indexOf( "(" );

                        if ( i != -1 ) {
                            String temp = "";
                            int tempcount = 0;

                            while ( true ) {
                                if ( line.charAt( i + 1 + tempcount ) == ')' )
                                    break;

                                temp += line.charAt( i + 1 + tempcount );

                                tempcount++;

                            }

                            Log.v( "check", line );
                            signalservers = temp;
                            //long k = pingS(temp,100,1,sl,timeout);
                            return timeforresponse;
                        }
                        else {
                            i = 4;
                            String temp = "";
                            int tempcount = 0;
                            Log.v( "check", line );

                            while ( true ) {
                                if ( line.charAt( i + 1 + tempcount ) == 'i' )
                                    break;

                                temp += line.charAt( i + 1 + tempcount );

                                tempcount++;

                            }

                            signalservers = "";

                            for ( int k = 0;k < temp.length() - 1;k++ ) {
                                signalservers += temp.charAt( k );
                            }

                            //Log.v("check",signalservers);
                            //long k = pingS(temp,100,1,sl,timeout);
                            return timeforresponse;
                        }
                    }

                    flag = true;





                }
                else if ( line.indexOf( "from" ) != -1 && tl == 1 ) {
                    Log.v( "PR", line );

                    if ( line.indexOf( "from" ) != -1 ) {
                        flag = true;
                        /*int i = line.indexOf("time=");
                        String temp="";
                        int tempcount = 0;
                        while(true)
                        {
                         if(line.charAt(i+5+tempcount)=='.'||line.charAt(i+5+tempcount)==' ')
                          break;
                         temp+=line.charAt(i+5+tempcount);
                         tempcount++;
                         
                        }

                        int k = new Integer(temp);
                        return k;*/ 
                        return timeforresponse;
                    }
                }
                else if ( line.indexOf( "from" ) != -1 ) {
                    flag = true;
                    destinationreached = true;
                    Log.v( "check", line );
                    return timeforresponse;
                }
                else {
                    break;
                }
            }

            input.close();
        }
        catch ( Exception e ) {}

        return -1;
    }


    class thread1 extends Thread {
        public void run() {
outer: {
                if ( DNSGOOGLE == true ) {
                    npopDNS = popDNSnames.length;

                    if ( checkstop() ) {
                        thread1doneflag = true;
                        return ;
                    }

                    replycode = DNSpopular();

                    if ( checkstop() ) {
                        thread1doneflag = true;
                        return ;
                    }

                    if ( replycode == 1 ) {
                        message1 = "Local DNS lookup latency (ms): Error in test";
                        break outer;
                    }

                    replycode = 0;
                    result = "DNS";
                    DNSlat = 0;
                    DNSlatyes = 0;

                    for ( int i = 0;i < popDNSnames.length;i++ ) {
                        result += ":";
                        result += "<LkUp" + i + ": " + DNSlatencies[ i ] + ">";
                        Log.v( TAG, " " + DNSlatencies[ i ] );

                        if ( DNSpop[ i ] == false ) {
                            replycode = 1;
                        }
                        else if ( DNSlatencies[ i ] > 50 ) {
                            DNSlat += DNSlatencies[ i ];
                            DNSlatyes++;
                        }
                    }

                    try {
                        Log.v( TAG, "PRINT " + message );
                        mStrings[ 0 ] = message;

                        if ( DNSlatyes > 0 ) {
                            message1 = "Local DNS lookup latency (ms): " + DNSlat / DNSlatyes;

                            if ( DNSlat / DNSlatyes < 200 )
                                message1 += " Good";
                            else if ( DNSlat / DNSlatyes < 500 )
                                message1 += " Moderate";
                            else
                                message1 += " Bad";
                        }
                        else {
                            message1 = "Local DNS lookup latency (ms): Error in test";
                        }

                        mProgressStatus = 30;
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message1 + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message1 + "\n" );

                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message1.length() + "!" + message1 + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                }
                else {
                    mProgressStatus = 30;

                    try {
                        message1 = "Local DNS lookup latency (ms): DNS server down";
                        fOut = openFileOutput( filename, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( "" + message1 + "\n" );
                        out.write( "" + mProgressStatus + "\n" );
                        out.close();
                        fOut.close();
                        fOut = openFileOutput( filename1, MODE_APPEND );
                        out = new OutputStreamWriter( fOut );
                        out.write( message1 + "\n" );
                        out.close();
                        fOut.close();
                        sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                    }
                    catch ( Exception e ) {}

                }

            }

            // Update the progress bar
            /*mHandler.post(new Runnable() {
                public void run() {
            mProgressStatus = 30;
                 mProgress.setProgress(mProgressStatus);
                 t2.setText(""+mProgressStatus+"% Complete");
                  t3.setText("Running test 5/11");
                 adapter.add(message);
                  lvw.setAdapter(adapter);
                  adapter.add(message1);
                  lvw.setAdapter(adapter);
                }
            });*/
            result += ";";
            Log.v( TAG, " " + result );
            result += "\n";
            sendReport( serverIP, result );

            if ( checkstop() ) {
                thread1doneflag = true;
                return ;
            }

            if ( pingflag ) {
                replycode = lat_landmark();

                if ( checkstop() ) {
                    thread1doneflag = true;
                    return ;
                }

                if ( replycode == 2 && avgpinglandmarkservers != 0 ) {
                    message = "Average Ping latency to landmark servers (ms): " + avgpinglandmarkservers;

                    if ( avgpinglandmarkservers < 200 )
                        message += " Good";
                    else if ( avgpinglandmarkservers < 500 )
                        message += " Moderate";
                    else
                        message += " Good";
                }
                else
                    message = "Average Ping latency to landmark servers (ms): Error";

                // Update the progress bar
            }
            else {
                message = "Average Ping latency to landmark servers (ms): Cannot run test, your provider blocks outgoing Ping Packets";
            }

            /*mHandler.post(new Runnable() {
             public void run(){
              adapter.add(message);
                   lvw.setAdapter(adapter);
             }
            });*/
            thread1doneflag = true;

            if ( checkstop() ) {
                thread1doneflag = true;
                return ;
            }
        }
    }

    class thread2 extends Thread {
        public void run() {
            if ( checkstop() ) {
                thread2doneflag = true;
                return ;
            }

            replycode = http_landmark();

            if ( checkstop() ) {
                thread2doneflag = true;
                return ;
            }

            do {
                if ( checkstop() ) {
                    thread2doneflag = true;
                    return ;
                }

                try {
                    Thread.sleep( 2000 );
                }
                catch ( InterruptedException e ) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            while ( thread1doneflag == false );

            if ( replycode == 2 ) {
                result = "LANDMARK";

                for ( int i = 0;i < nlandmarkservers;i++ ) {
                    result += ":";
                    result += "<PingRTT" + i + ": " + latencylandmarkservers[ i ] / 10.0 + ">:<PingLR" + i + ": " + ( 2 - lossratelandmarkservers[ i ] ) + "/2>";
                    result += ":<HdSk" + i + ": " + synacklandmarkservers[ i ] + ">";
                    result += ":<Latency" + i + ": " + gettlandmarkservers[ i ] + ">:<Size" + i + ": " + getslandmarkservers[ i ] + ">";
                }

                result += ";";
                Log.v( TAG, result );
                result += "\n";
                sendReport( serverIP, result + "\n" );

                if ( avghttplandmarkservers != 0 ) {
                    message = "Average TCP handshake latency to landmark server (ms): " + avghttplandmarkservers;

                    if ( avghttplandmarkservers < 200 )
                        message += " Good";
                    else if ( avghttplandmarkservers < 500 )
                        message += " Moderate";
                    else
                        message += " Bad";
                }
                else
                    message = "Average TCP handshake latency to landmark server (ms): Error in test";

                if ( avghttplandmarkservers2 != 0 ) {
                    message1 = "Average HTTP GET latency to landmark servers (ms): " + avghttplandmarkservers2;

                    if ( avghttplandmarkservers2 < 400 )
                        message1 += " Good";
                    else if ( avghttplandmarkservers2 < 800 )
                        message1 += " Moderate";
                    else
                        message1 += " Bad";
                }
                else
                    message1 = "Average HTTP GET latency to landmark servers (ms): Error in test";

            }
            else {
                message = "Average TCP handshake latency to landmark server (ms): Error in test";
                message1 = "Average HTTP GET latency to landmark servers (ms): Error in test ";
            }

            mProgressStatus = 45;

            try {
                fOut = openFileOutput( filename, MODE_APPEND );
                out = new OutputStreamWriter( fOut );
                out.write( message + "\n" );
                out.write( "" + mProgressStatus + "\n" );
                sendudpmessage( "uiprint.txt", "" + message.length() + "!" + message + "" + mProgressStatus + "!" );
                out.write( "" + message1 + "\n" );
                out.write( "" + mProgressStatus + "\n" );
                out.close();
                fOut.close();
                fOut = openFileOutput( filename1, MODE_APPEND );
                out = new OutputStreamWriter( fOut );
                out.write( message + "\n" );
                out.write( message1 + "\n" );
                out.close();
                fOut.close();
                sendudpmessage( "uiprint.txt", "" + message1.length() + "!" + message1 + "" + mProgressStatus + "!" );

            }
            catch ( Exception e ) {}

            thread2doneflag = true;

            if ( checkstop() ) {
                thread2doneflag = true;
                return ;
            }

        }
    }

    // latency 2nd hop
    int lat_2ndhop() {

        Log.d( TAG, "in 2nd hp" );

        for ( int i = 0;i < 3;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            signalservers = null;
            lossrateservers[ 0 ] = 0;
            pingS( "www.google.com", i + 1, 0, 0, 2000 );

            if ( signalservers != null ) {
                result = "TRACERT:<DEST: www.google.com>:<1STIP: " + signalservers + ">;";
                sendReport( serverIP, result );
                Log.v( TAG, result );
                result = "";

                for ( int j = 0;j < 10;j++ ) {
                    if ( checkstop() ) {
                        return 1;
                    }

                    long reply = pingS( signalservers, 1, 1, 0, 2000 );

                    if ( reply != -1 )
                        latencyservers[ 0 ] += reply;
                    else
                        lossrateservers[ 0 ] ++;

                    if ( j == 0 ) {
                        result = "SIGNAL:";
                    }

                    result += "<RTT:" + reply + ">";

                    if ( j == 9 )
                        result += ";";
                    else
                        result += ":";

                }

                sendReport( serverIP, result );
                return 2;
            }
        }

        return 1;
    }



    // landmark

    int lat_landmark() {
        completepinglandrmarkservers = 0;
        successpinglandmarkservers = 0;
        avgpinglandmarkservers = 0;

        if ( pingS( "www.google.com", 5, 1, 0, 4000 ) == -1 ) {
            for ( int i = 0;i < nlandmarkservers;i++ ) {
                latencylandmarkservers[ i ] = -1 ;
                lossratelandmarkservers[ i ] = 2;
            }

            return 1;
        }

        if ( checkstop() ) {
            return 1;
        }

        for ( int i = 0;i < nlandmarkservers;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            //new lat_landmark_thread(i).start();
            latencylandmarkservers[ i ] = 0 ;

            lossratelandmarkservers[ i ] = 0;

            for ( int j = 0;j < 2;j++ ) {
                if ( checkstop() ) {
                    return 1;
                }

                long reply = pingS( landmarkservers[ i ], 1, 1, i, 2000 );
                Log.v( TAG, "reply is " + reply );

                if ( reply != -1 ) {
                    latencylandmarkservers[ i ] += reply;
                    successpinglandmarkservers++;
                    avgpinglandmarkservers += reply;
                }
                else {
                    lossratelandmarkservers[ i ] ++;
                }
            }
        }

        if ( checkstop() ) {
            return 1;
        }

        if ( successpinglandmarkservers != 0 )
            avgpinglandmarkservers /= successpinglandmarkservers;

        return 2;
    }

    int http_landmark() {
        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        long strTime = 0, endTime;
        boolean flag = false;
        avghttplandmarkservers = 0;
        avghttplandmarkservers2 = 0;
        successhttplandmarkservers = 0;

        if ( checkstop() ) {
            return 1;
        }

        if ( checkstop() ) {
            return 1;
        }

        for ( int i = 0;i < nlandmarkservers;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            synacklandmarkservers[ i ] = -1;
            getslandmarkservers[ i ] = -1;
            gettlandmarkservers[ i ] = -1;

            try {
                tcpSocket = new Socket();
                SocketAddress remoteAddr = new InetSocketAddress( landmarkservers[ i ], 80 );
                strTime = time();
                tcpSocket.connect( remoteAddr, 2000 );
                endTime = time();
                synacklandmarkservers[ i ] = endTime - strTime;
                avghttplandmarkservers += synacklandmarkservers[ i ];
                successhttplandmarkservers++;
                os = new DataOutputStream( tcpSocket.getOutputStream() );
                is = new DataInputStream( tcpSocket.getInputStream() );
                tcpSocket.setSoTimeout( 2000 );
                tcpSocket.setTcpNoDelay( true );
            }
            catch ( UnknownHostException e ) {
                //TODO
                Log.v( TAG, "http_landmark: cannot resolve tcp host " + landmarkservers[ i ] );
            }
            catch ( Exception e ) {
                //TODO
                Log.v( TAG, "http_landmark: cannot get the I/O for tcp connection " + landmarkservers[ i ] );
            }

            if ( tcpSocket == null || os == null || is == null ) {
                //TODO
                Log.v( TAG, "http_landmark: tckpSocket or os or is null " + landmarkservers[ i ] );
            }

            else {
                int len = 0;
                String buf = "GET /index.html HTTP/1.1\r\nHost:" + landmarkservers[ i ] + "\r\nAccept-Encoding: gzip\r\n\r\n";
                byte[] message = buf.getBytes();
                flag = false;
                endTime = time();

                try {
                    byte[] buffer = new byte[ 100000 ];
                    int read_bytes = 0;
                    os.write( message );
                    strTime = time();

                    do {
                        read_bytes = is.read( buffer, 0, 100000 );

                        if ( checkstop() ) {
                            return 1;
                        }

                        if ( read_bytes != -1 ) {
                            endTime = time();
                            tcpSocket.setSoTimeout( 1000 );
                            len += read_bytes;
                        }
                    }
                    while ( read_bytes > 0 );
                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    Log.v( TAG, "http_landmark: error sending data " + landmarkservers[ i ] + "  " + e.getMessage() );
                }

                if ( len > 0 ) {
                    getslandmarkservers[ i ] = len;
                    gettlandmarkservers[ i ] = endTime - strTime;
                    avghttplandmarkservers2 += gettlandmarkservers[ i ];
                }

                try {
                    tcpSocket.close();
                    os.close();
                    is.close();
                }
                catch ( Exception e2 ) {
                    // TODO Auto-generated catch block
                    Log.v( TAG, "http_landmark: error closing tcp socket" );
                }
            }

        }

        if ( successhttplandmarkservers != 0 ) {
            avghttplandmarkservers /= successhttplandmarkservers;
            avghttplandmarkservers2 /= successhttplandmarkservers;
        }

        return 2;


    }

    class http_caching_thread extends Thread {
        String filename;
        public http_caching_thread( String name ) {
            super();
            filename = name;
        }

        public void run() {
            if ( checkstop() ) {
                return ;
            }

            Socket tcpSocket = null;
            DataOutputStream os = null;
            DataInputStream is = null;

            try {
                tcpSocket = new Socket();
                SocketAddress remoteAddr = new InetSocketAddress( httpserverIP, 80 );
                tcpSocket.connect( remoteAddr, 4000 );
                os = new DataOutputStream( tcpSocket.getOutputStream() );
                is = new DataInputStream( tcpSocket.getInputStream() );
                tcpSocket.setSoTimeout( 2000 );
                tcpSocket.setTcpNoDelay( true );
            }
            catch ( UnknownHostException e ) {
                //TODO
                Log.v( TAG, "http_caching: cannot resolve tcp host " );
                ncachingcomplete++;
                return ;
            }
            catch ( Exception e ) {
                //TODO
                Log.v( TAG, "http_caching: cannot get the I/O for tcp connection " );
                ncachingcomplete++;
                return ;
            }

            if ( tcpSocket == null || os == null || is == null ) {
                //TODO
                Log.v( TAG, "http_caching: tckpSocket or os or is null " );
                ncachingcomplete++;
                return ;
            }

            int len = 0;

            String buf = "GET /" + filename + " HTTP/1.1\r\nHost:" + "googleftps.com" + "\r\nAccept-Encoding: gzip\r\n\r\n";
            byte[] message = buf.getBytes();

            try {
                byte[] buffer = new byte[ 10000 ];
                int read_bytes = 0;
                os.write( message );
                int flag = 0;

                do {
                    read_bytes = is.read( buffer, 0, 10000 );

                    if ( read_bytes <= 0 )
                        break;

                    len += read_bytes;

                    String reply = new String( buffer, 0, read_bytes );

                    if ( reply != null ) {
                        if ( reply.indexOf( "Content-Encoding: gzip" ) != -1 || reply.indexOf( "Vary: Accept-Encoding" ) != -1 )
                            compressionflag = true;
                    }

                    if ( read_bytes > 0 ) {
                        if ( flag == 0 ) {
                            flag = 1;
                            ncachingsuccess++;
                        }

                        tcpSocket.setSoTimeout( 200 );
                    }

                }
                while ( read_bytes > 0 );
            }
            catch ( Exception e ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "http_caching: error sending data up " + e.getMessage() );
                //return 4;
            }

            try {
                tcpSocket.close();
                os.close();
                is.close();
            }
            catch ( Exception e2 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "http_caching: error closing tcp socket" );
                ncachingcomplete++;
                return ;
            }

            ncachingcomplete++;
            return ;
        }

    }

    // http caching and compression
    int http_caching() {

        ncachingsuccess = 0;
        ncachingcomplete = 0;
        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        cachflag = false;
        int nsuccess = 0;
        compressionflag = false;

        Random generator = new Random();
        int r = generator.nextInt( 10000 );
        String filename = "index" + r + ".html";

        for ( int i = 0;i < cachtimes;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            new http_caching_thread( filename ).start();
        }

        if ( checkstop() ) {
            return 1;
        }

        do {
            try {
                if ( checkstop() ) {
                    return 1;
                }

                Thread.sleep( 1000 );
            }
            catch ( InterruptedException e ) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        while ( ncachingcomplete != cachtimes );

        if ( checkstop() ) {
            return 1;
        }

        Log.v( TAG, "total success " + ncachingsuccess );
        // getting result

        try {
            tcpSocket = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress( httpserverIP, PORT_CACHING );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );
            tcpSocket.setTcpNoDelay( true );
        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "http_caching: cannot resolve tcp host " );
            return 6;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "http_caching: cannot get the I/O for tcp connection " );
            return 7;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "http_caching: tckpSocket or os or is null " );
            return 8;
        }

        byte[] message = filename.getBytes();

        int retval = -1;
outer: {
            try {
                byte[] buffer = new byte[ 10000 ];
                int read_bytes = 0;
                os.write( message );
                read_bytes = is.read( buffer, 0, 10000 );

                if ( read_bytes <= 0 ) {
                    retval = 9;
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                int i = 0;
                String temp = "";

                while ( i < reply.length() ) {
                    if ( reply.charAt( i ) == ' ' )
                        break;

                    temp += reply.charAt( i++ );

                }

                int ntimes = new Integer( temp );

                if ( ntimes < nsuccess )
                    cachflag = true;
            }
            catch ( Exception e ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "http_caching: error sending data " + e.getMessage() );
                retval = 10;
                break outer;
            }
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();

            if ( retval != -1 )
                return retval;
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "http_caching: error closing tcp socket" );

            if ( retval != -1 )
                return retval;
            else
                return 11;
        }

        return 12;

    }




    // time

    long time() {
        return System.currentTimeMillis();
    }





    // performance tests:




    int MeasureUplinkTput( String tcpserverIP ) {

        uplinksize = -1;


        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;

        try {
            tcpSocket = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress( tcpserverIP, PORT_THRU_UP );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );
            tcpSocket.setTcpNoDelay( true );


        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "MeasureUplinkTput: cannot resolve tcp host" );
            return 1;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "MeasureUplinkTput: cannot get the I/O for tcp connection" );
            return 2;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "MeasureUplinkTput: tckpSocket or os or is null" );
            return 3;
        }

        int retval = -1;
outer: {
            if ( checkstop() ) {
                break outer;
            }

            // tcp uplink
            long len = 0;

            long count = 0;

            String buf = "ehcsinmfuevrxruudycdbgdyrlmbapvxpbmzshhkrtewlijrlzbcfobxxugvnjqehdpnsiuwqnbhshrgfgivdyafowedzjlxwxavfsbvzqdddaiorpnpmunqzihrgewqebvnymvujrylymgwliovsyyoozkdgcskedzmhxijruaaurpocsnxtitlcvotrxpvnzwornmoicpaxbobfoehwvirpannjeizbtkizvdgmhgjjkljmjkculysjdvfnsranueaizstwrtuszgfknbsarwkfsrcuhjvzhvcduabphnusscfvqyqpfyndbplpklrwqrpgyitigaeowfnxnfvysdrwjpvbustrltyoqrtunmnxxenmyudvatlevpzsqmfwlzdsglthvwfvldylyktapinzkztygsbzfnbeiimstfjgppamkimryjnxmojdiezuhkvjzgqrfcmhrgcaqyqktvsdxnyptamfmsvghunxbeqlydmnkeqgzgdjjyemgmgxrlsczsuzenyeozgvhhrdawzgvgjueaykkcqlswfcjozucztcyynorcarkhsbgmzodkxjbdejbtxldpaoapyithrskisxyrrcrbuaezveueikvppwzvyvloytphbztcumodlhmvcwdqwtgtnnmlnhmdvpsrnfbbzydikyvamnzxudoeppvhonysvzjccfatxyosaumvgkxdpwsjbtpqcscfyqzruztafodqhfywacsqocckdlssrpnvoycecwvzzsyzbwmnkfpvupudfhrocunyzpytdtvznuskauhaancoylvcezzbgnrayvhwxjocckahppqhotpoccserezellvwijjdqfakcvjknxnjnibdyugxfpsnsrgxmkgbsjyynrdfdifcrxvgcyvtbseipkxhlajjpsmoqjdijeoudfvqpfjwjixfzgdhnkhyahdiuezbpxyjqhblahgwyqosjjqcdbvbqdabrxgmirbtv";

            byte [] message = prefix.getBytes();

            try {
                os.write( message );
            }
            catch ( Exception e3 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "MeasureUplinkTput: error in sending prefix" );
                retval = 4;
                break outer;
            }

            try {
                Thread.sleep( 2000 );
            }
            catch ( InterruptedException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            message = buf.getBytes();
            long startTime = time(), endTime = time();

            do {
                if ( checkstop() ) {
                    break outer;
                }

                count++;

                try {
                    os.write( message );
                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    Log.v( TAG, "MeasureUplinkTput: error sending data " + e.getMessage() );
                    retval = 5;
                    break outer;
                }

                endTime = time();


            }
            while ( ( endTime - startTime ) / 1000 < 8 );

            uplinksize = count * ( message.length );
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();

            if ( retval != -1 )
                return retval;
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "MeasureUplinkTput: error closing tcp socket" );

            if ( retval != -1 )
                return retval;
            else
                return 6;

        }

        Log.v( TAG, "MeasureUplinkTput: everything perfect " );
        return 7;
    }

    int MeasureDownlinkTput( String tcpserverIP ) {
        downlinksize = -1;
        downlinktime = -1;

        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;

        try {
            tcpSocket = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress( tcpserverIP, PORT_THRU_DOWN );
            tcpSocket.connect( remoteAddr, 4000 );
            tcpSocket.setSoTimeout( 4000 );
            tcpSocket.setTcpNoDelay( true );

            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "MeasureUplinkTput: cannot resolve tcp host" );
            return 1;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "MeasureUplinkTput: cannot get the I/O for tcp connection" );
            return 2;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "MeasureUplinkTput: tckpSocket or os or is null" );
            return 3;
        }

        int retval = -1;
outer: {
            if ( checkstop() ) {
                break outer;
            }

            // getting downlink data
            byte [] message = prefix.getBytes();

            try {

                os.write( message );

            }
            catch ( Exception e3 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "MeasureDownlinkTput: error in sending prefix" );
                retval = 4;
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            long startTime = time();
            long endTime = time();
            long endTime2 = time();
            long total_read_bytes = 0;

            do {
                if ( checkstop() ) {
                    break outer;
                }

                try {
                    byte[] buffer = new byte[ 15000 ];


                    int read_bytes = is.read( buffer, 0, 15000 );

                    if ( read_bytes <= 0 )
                        break;

                    total_read_bytes += read_bytes;


                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.v( TAG, "MeasureDownlinkTput: error in receiving data" + e.getMessage() );
                    break;
                }

                endTime = time();
            }
            while ( true );

            if ( total_read_bytes > 1000 ) {
                Log.v( TAG, "MeasureDownlinkTput: downlink time is " + ( endTime - startTime ) + " " + total_read_bytes + " " + ( endTime2 - startTime ) );
            }
            else {
                Log.v( TAG, "MeasureDownlinkTput:did not receive enough data " + total_read_bytes );
                retval = 5;
                break outer;
            }

            long timespent = ( endTime - startTime );
            downlinksize = total_read_bytes;
            downlinktime = timespent;
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();

            if ( retval != -1 )
                return retval;
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "MeasureTput: error closing tcp socket" );

            if ( retval != -1 )
                return retval;
            else
                return 6;

        }





        Log.v( TAG, "everything great" );

        return 7;

    }



    int DNSReqGoogle() {
        InetAddress addrDNS = null;
        DNSgoogle = false;

        try {
            addrDNS = InetAddress.getByName( "www.yahoo.com" );
        }
        catch ( Exception e ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "DNSReqGoogle: error in resolving GOOGLE" );
            return 2;
        }

        if ( addrDNS == null ) {
            Log.v( TAG, "DNSReqGoogle: dns server down" );
            return 3;
        }


        DNSGOOGLE = true;
        return 4;
    }

    InetAddress addrDNS;
    String hostname;


    long checkDNS( String name, String address ) {
        addrDNS = null;
        hostname = name;
        long strttime, endtime;
        strttime = time();
        mHandler.post( new Runnable() {
                           public void run() {
                               try {
                                   addrDNS = InetAddress.getByName( hostname );
                               }
                               catch ( UnknownHostException e ) {}

                           }

                       }

                     );

        endtime = time();

        while ( endtime - strttime < 2000 && addrDNS == null ) {
            endtime = time();
        }

        Log.v( TAG, " " + ( endtime - strttime ) );
        return ( endtime -strttime );


    }

    int DNSpopular() {
        Socket tcpSocket = null;


        if ( checkstop() ) {
            return 1;
        }

        for ( int i = 0;i < popDNSnames.length;i++ ) {
            if ( checkstop() ) {
                return 1;
            }

            DNSpop[ i ] = false;
            long flag = 3000;
            DNSlatencies[ i ] = 0;

            for ( int j = 0;j < 2;j++ ) {
                flag = checkDNS( popDNSnames[ i ], popDNSaddresses[ i ] );

                if ( flag < 2000 ) {
                    DNSlatencies[ i ] = flag;
                    DNSpop[ i ] = true;
                    break;
                }
            }

            if ( flag >= 2000 ) {
                //TODO
                Log.v( TAG, "DNSpopular: cannot resolve DNS name: " + popDNSnames[ i ] );
                DNSpop[ i ] = false;
            }
        }

        return 2;
    }


    int DNS_UMICH( String udpserverIP ) {

        DNSUMICH = false;

        InetAddress udpaddress;

        try {
            udpaddress = InetAddress.getByName( udpserverIP );
        }
        catch ( UnknownHostException e1 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "DNS_UMICH: udp server unknown" );
            return 2;
        }

        byte [] udpmessage = new byte[] {56, 44, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 103, 111, 3, 99, 111, 109, 0, 0, 1, 0, 1};

        DatagramPacket packet = new DatagramPacket( udpmessage, udpmessage.length, udpaddress, PORT_DNS_UDP );
        DatagramSocket udpSocket = null;

        try {
            udpSocket = new DatagramSocket();
            udpSocket.setSoTimeout( 4000 );
            udpSocket.send( packet );

        }
        catch ( Exception e ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "DNS_UMICH : cannot open udp socket or send packet " + e.getMessage() );
            return 3;
        }

        byte[] buffer = new byte[ 2048 ];
        DatagramPacket packetr = new DatagramPacket( buffer, buffer.length );

        try {
            udpSocket.receive( packetr );
        }
        catch ( Exception e ) {
            Log.v( TAG, "DNS_UMICH: got exception receiving " + e.getMessage() );
            return 4;
        }

        udpSocket.close();

        if ( packetr.getAddress().getHostAddress().toString().equals( udpaddress.getHostAddress().toString() ) ) {
            Log.v( TAG, "data got is " + packetr.getData().toString() );
            Log.v( TAG, "data got is " + packetr.getData().length );

            if ( packetr.getData().toString().equals( "original!" ) ) {
                Log.v( TAG, "DNS_UMICH: got correct reply " );
                DNSUMICH = true;
            }

            return 5;
        }
        else {
            Log.v( TAG, "DNS_UMICH: got wrong reply" );
            return 6;
        }

    }


    // bit torrent


    int BTptosUp( String serverIP, int port ) {
        btblockedstage = "S";
        int nofPackets = 0;
        boolean timeoutflag = false;
        char [] cs = new char[ 1000 ];
        int [] size = new int[ 1000 ];
        // reading size file

        if ( checkstop() ) {
            return 1;
        }

        try {
            InputStream reader = null;
            reader = this.getResources().openRawResource( R.raw.bts );
            byte[] buffer = new byte[ 1000 ];

            while ( reader.available() != 0 ) {
                if ( checkstop() ) {
                    return 1;
                }

                String line = "";
                char c;

                do {
                    reader.read( buffer, 0, 1 );
                    c = ( char ) buffer[ 0 ];

                    if ( c != '\n' )
                        line += c;
                }
                while ( c != '\n' );

                cs[ nofPackets ] = line.charAt( 0 );

                String temp = "";

                int j = 0;

                String leng = "" + line.charAt( 2 );

                int l = new Integer( leng );

                while ( j < l ) {
                    temp += line.charAt( 3 + j );
                    j++;
                }

                size[ nofPackets++ ] = new Integer( temp );
            }
        }
        catch ( Exception e ) {
            //TODO Auto-generated catch block
            Log.v( TAG, "BTptosU: error in opening size file " + e.getMessage() );
            return 1;
        }

        if ( checkstop() ) {
            return 1;
        }

        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;

        try {
            tcpSocket = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress( serverIP, port );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );

        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "BTptosU: cannot resolve tcp host" );
            btblockedstage = "SYN";
            return 2;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "BTptosU: cannot get the I/O for tcp connection" );
            btblockedstage = "SYN";
            return 3;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "BTptosU: tckpSocket or os or is null" );
            btblockedstage = "SYN";
            return 4;
        }

outer: {
            if ( checkstop() ) {
                break outer;
            }

            InputStream reader = null;

            try {
                reader = this.getResources().openRawResource( R.raw.bt );
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "bt file not found" );
                break outer;
            }

            //sending prefix and getting reply
            try {
                if ( checkstop() ) {
                    break outer;
                }

                byte [] message = prefix.getBytes();
                os.write( message );

                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "PrefixOK" ) == false ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosU: error sending prefix" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            try {
                byte [] message = "UplinkStart".getBytes();
                os.write( message );

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosU: error sending uplink" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            byte [] buf = new byte[ 10000 ];
            //sending actual data now

            try {
                Thread.sleep( 2000 );
            }
            catch ( InterruptedException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            if ( checkstop() ) {
                break outer;
            }

            long strt, end;
            strt = time();

            for ( int i = 0;i < nofPackets;i++ ) {
                if ( checkstop() ) {
                    break outer;
                }

                if ( cs[ i ] == 's' ) {
                    try {
                        reader.read( buf, 0, size[ i ] );
                        os.write( buf, 0, size[ i ] );

                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();

                        if ( i == 1 )
                            btblockedstage = "Hdsk";

                        if ( i == 3 )
                            btblockedstage = "Cont";

                        if ( i >= 5 )
                            btblockedstage = "Req";

                        Log.v( TAG, "BTptosU: error sending actual data " + e.getMessage() );

                        break outer;
                    }
                }
                else {
                    try {
                        byte[] buffer = new byte[ 1000 ];
                        int len = 0;

                        if ( size[ i ] > 1000 ) {
                            do {
                                int read_bytes = is.read( buffer, 0, 1000 );
                                len += read_bytes;

                                if ( checkstop() ) {
                                    timeoutflag = true;
                                    break outer;
                                }

                                if ( read_bytes <= 0 ) {

                                    if ( i == 0 )
                                        btblockedstage = "Hdsk";

                                    if ( i == 2 )
                                        btblockedstage = "Cont";

                                    if ( i >= 4 )
                                        btblockedstage = "Piece";

                                    break outer;
                                }
                            }
                            while ( size[ i ] - len > 1000 );
                        }

                        do {
                            int read_bytes = is.read( buffer, 0, size[ i ] - len );
                            len += read_bytes;

                            if ( checkstop() ) {
                                timeoutflag = true;
                                break outer;
                            }

                            if ( read_bytes <= 0 ) {
                                if ( i == 0 )
                                    btblockedstage = "Hdsk";

                                if ( i == 2 )
                                    btblockedstage = "Cont";

                                if ( i >= 4 )
                                    btblockedstage = "Piece";

                                break outer;
                            }
                        }
                        while ( size[ i ] - len != 0 );

                        end = time();

                        if ( end - strt > 8000 ) {
                            timeoutflag = true;
                            break;
                        }

                        //String reply = new String(buffer,0,read_bytes);
                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        Log.v( TAG, "BTptosU: error receiving actual data " + e.getMessage() );
                        e.printStackTrace();

                        if ( i == 0 )
                            btblockedstage = "Hdsk";

                        if ( i == 2 )
                            btblockedstage = "Cont";

                        if ( i >= 4 )
                            btblockedstage = "Piece";

                        break outer;
                    }
                }
            }
        }

        if ( timeoutflag ) {
            try {
                byte [] message = "UplinkDone".getBytes();
                os.write( message );

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "E";
                Log.v( TAG, "BTptosD: error sending downlink" );
                return 12;
            }
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "BTptosU: error closing tcp socket" );
            btblockedstage = "E";
            return 13;

        }

        if ( btblockedstage.equals( "S" ) ) {
            btblockedstage = "E";
            Log.v( TAG, "BTptosU: everything great " );
        }

        return 14;

    }

    int BTptosDown( String serverIP, int port ) {
        btblockedstage = "S";
        int nofPackets = 0;
        List<Integer> list = new ArrayList<Integer>();
        char [] cs = new char[ 1000 ];
        int [] size = new int[ 1000 ];
        int l = 0;
        boolean timeoutflag = false;
        // reading size file

        try {
            if ( checkstop() ) {
                return 1;
            }

            InputStream reader = null;
            reader = this.getResources().openRawResource( R.raw.bts );
            byte[] buffer = new byte[ 1000 ];

            while ( reader.available() != 0 ) {
                if ( checkstop() ) {
                    return 1;
                }

                String line = "";
                char c;

                do {
                    reader.read( buffer, 0, 1 );
                    c = ( char ) buffer[ 0 ];

                    if ( c != '\n' )
                        line += c;
                }
                while ( c != '\n' );

                cs[ nofPackets ] = line.charAt( 0 );

                String temp = "";

                int j = 0;

                String leng = "" + line.charAt( 2 );

                int lk = new Integer( leng );

                while ( j < lk ) {
                    temp += line.charAt( 3 + j );
                    j++;
                }

                size[ nofPackets++ ] = new Integer( temp );
            }
        }
        catch ( Exception e ) {
            //TODO Auto-generated catch block
            Log.v( TAG, "BTptosD: error in opening size file " + e.getMessage() );
            return 1;
        }

        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;

        try {
            if ( checkstop() ) {
                return 1;
            }

            tcpSocket = new Socket();

            SocketAddress remoteAddr = new InetSocketAddress( serverIP, port );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );

        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "BTptosD: cannot resolve tcp host" );
            btblockedstage = "SYN";
            return 2;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "BTptosD: cannot get the I/O for tcp connection" );
            btblockedstage = "SYN";
            return 3;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "BTptosD: tckpSocket or os or is null" );
            btblockedstage = "SYN";
            return 4;
        }

outer: {

            if ( checkstop() ) {
                break outer;
            }

            InputStream reader = null;

            try {
                reader = this.getResources().openRawResource( R.raw.btsvr );
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "bt file not found" );
                break outer;
            }

            //sending prefix and getting reply
            try {
                byte [] message = prefix.getBytes();
                os.write( message );
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "PrefixOK" ) == false ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosD: got wrong reply for prefix" );
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosD: error sending prefix" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            try {

                byte [] message = "Downlink".getBytes();

                os.write( message );

                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "DownlinkOK" ) == false ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosD: got wrong reply for downlink" );
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosD: error sending downlink" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            byte [] buf = new byte[ 10000 ];
            //sending actual data now
            int count = 0;

            try {
                Thread.sleep( 2000 );
            }
            catch ( InterruptedException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            long strt, end;
            strt = time();

            if ( checkstop() ) {
                break outer;
            }

            for ( int i = 0;i < nofPackets;i++ ) {
                if ( checkstop() ) {
                    break outer;
                }

                if ( cs[ i ] == 'c' ) {
                    try {
                        reader.read( buf, 0, size[ i ] );
                        os.write( buf, 0, size[ i ] );


                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Log.v( TAG, "BTptosD: error sending actual data " + e.getMessage() );

                        if ( i == 0 )
                            btblockedstage = "Hdsk";

                        if ( i == 2 )
                            btblockedstage = "Cont";

                        if ( i >= 4 )
                            btblockedstage = "Req";

                        break outer;
                    }
                }
                else {
                    try {
                        byte[] buffer = new byte[ 1000 ];
                        int len = 0;

                        if ( size[ i ] > 1000 ) {
                            do {
                                int read_bytes = is.read( buffer, 0, 1000 );
                                len += read_bytes;

                                if ( checkstop() ) {
                                    timeoutflag = true;
                                    break outer;
                                }

                                if ( read_bytes <= 0 ) {
                                    if ( i == 1 )
                                        btblockedstage = "Hdsk";

                                    if ( i == 3 )
                                        btblockedstage = "Cont";

                                    if ( i >= 5 )
                                        btblockedstage = "Piece";

                                    break outer;
                                }
                            }
                            while ( size[ i ] - len > 1000 );
                        }

                        do {
                            int read_bytes = is.read( buffer, 0, size[ i ] - len );

                            if ( checkstop() ) {
                                timeoutflag = true;
                                break outer;
                            }

                            count++;

                            if ( read_bytes <= 0 ) {
                                if ( read_bytes <= 0 ) {
                                    if ( i == 1 )
                                        btblockedstage = "Hdsk";

                                    if ( i == 3 )
                                        btblockedstage = "Cont";

                                    if ( i >= 5 )
                                        btblockedstage = "Piece";

                                    break outer;
                                }
                            }

                            len += read_bytes;

                        }
                        while ( size[ i ] - len != 0 );

                        end = time();

                        if ( end - strt > 8000 ) {
                            timeoutflag = true;
                            break outer;
                        }

                        //String reply = new String(buffer,0,read_bytes);
                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        Log.v( TAG, "BTptosD: error receiving actual data " + e.getMessage() );
                        e.printStackTrace();

                        if ( i == 1 )
                            btblockedstage = "Hdsk";

                        if ( i == 3 )
                            btblockedstage = "Cont";

                        if ( i >= 5 )
                            btblockedstage = "Piece";

                        break outer;

                    }
                }
            }
        }

        if ( timeoutflag ) {

            try {
                byte [] message = "DownlinkDone".getBytes();
                os.write( message );
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "E";
                Log.v( TAG, "BTptosD: error sending downlink" );
            }
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "BTptosD: error closing tcp socket" );
            return 10;

        }


        if ( btblockedstage.equals( "S" ) ) {
            btblockedstage = "E";
            Log.v( TAG, "BTptosD: everything great " );
        }

        return 11;

    }

    int BTRandom( String serverIP ) {

        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        int retval = -1;

        try {
            if ( checkstop() ) {
                return 1;
            }

            tcpSocket = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress( serverIP, PORT_BT );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );

        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "BTRandom: cannot resolve tcp host" );
            return 2;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "BTRandom: cannot get the I/O for tcp connection" );
            return 3;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "BTRandom: tckpSocket or os or is null" );
            return 4;
        }

outer: {
            if ( checkstop() ) {
                break outer;
            }

            //sending prefix and getting reply
            try {
                byte [] message = prefix.getBytes();
                os.write( message );
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    retval = 5;
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "PrefixOK" ) == false ) {
                    Log.v( TAG, "BTRandom: got wrong reply for prefix" );
                    retval = 5;
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "BTRandom: error sending prefix" );
                retval = 5;
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            try {
                byte [] message = "Random".getBytes();
                os.write( message );
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    retval = 6;
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "RandomOK" ) == false ) {
                    Log.v( TAG, "BTRandom: got wrong reply for Random" );
                    retval = 6;
                    break outer;
                }
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "BTRandom: error sending random" );
                retval = 6;
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            try {
                Thread.sleep( 2000 );
            }
            catch ( InterruptedException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            //sending actual data now
            if ( checkstop() ) {
                break outer;
            }

            long strt, end;
            strt = time();

            Log.v( TAG, "sending actual data" );
            String str = "otamoomhvzspkkgraexgrvygrtvvpgplucbufwwrsmgbjjvnlokorclxrlddqaoseybhgcehgedjburvnkedyrwssftusyghcikqqqqqojivkhlbeluzfzbtoyvaehpvkcjoxvvgwhlzhlxqrhfkwmhltecyovgxmtfsptdpfusxbfcozscxvtsocpfnfdyvlwppdlxsfipxkocfbajigpwxbgkxmmcuqsigwfipiumkmilvjvygappzhsfvtxtanzgljbifugscjnkpcxtyvvyxypspclrkqvjrauslthqjnodoymfzetqtmfwtxothviehvyurpajwwaekvmntbnpaotytafroxvotjdvelggkppgqhmprglvghkqctorugxnggtdbdszdwdheqjbduqgfrwznrlwzymklorilcutzgcouwtpeobkyigulbxlgcyirslptakxfpfjfeijzfsqjktdxcxkxfxtfmrmibajgekqcqnzbmbfzzglkbjlsaxovhkyhxfwbczctymjdmwfucrjitmaoqlcsxhiqxedivyimvgbalcyrdqfjhgvzqlpjzkzrgnfderlufdyypamtaqngdgiqrqxdlrxoopkxhywhyouskylddeawhqudjnitlpqdxtdocwdltwoubreyegrnulfxaiwzfwqdrydwzpjwgojaarypkiwhmfwzgkpasslldpaamrrnpqhtxcpdcyibypyvhthlryptuxysoeywvndpznjegisgvnhvuujcbxonizqaxrudysgxfjxroswjilquwmdvjztwuopcowydbferebriqdafuwatmqbntxhcszpovbqdtuuyzgkylkpyxbiztlnksbihxehmialyrtlehebhbmwywhhiwiuuuagbecjojleoqxuwyluyosfauvlteazqulwvkjtmpaiqmrdpoahsgxjdptubfuryucsbbbwoyfjlrpzgkkkvfbbxxmbbobowckvxlzrpohsdzzukrexcyuwwhbxv";

            byte[] message = str.getBytes();

            do {

                if ( checkstop() ) {
                    break outer;
                }

                try {
                    os.write( message );

                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.v( TAG, "BTRandom: error sending actual data " + e.getMessage() );
                    retval = 7;
                    break outer;
                }


                try {
                    byte[] buffer = new byte[ 1000 ];
                    int len = 0;
                    int size = str.length();

                    if ( checkstop() ) {
                        break outer;
                    }

                    if ( size > 1000 ) {
                        do {
                            int read_bytes = is.read( buffer, 0, 1000 );
                            len += read_bytes;

                            if ( read_bytes <= 0 ) {
                                retval = 8;
                                break outer;
                            }
                        }
                        while ( size - len > 1000 );
                    }

                    do {
                        if ( checkstop() ) {
                            break outer;
                        }

                        int read_bytes = is.read( buffer, 0, size - len );

                        if ( read_bytes <= 0 ) {
                            retval = 8;
                            break outer;
                        }

                        len += read_bytes;

                    }
                    while ( size - len != 0 );


                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    Log.v( TAG, "BTRandom: error receiving actual data " + e.getMessage() );
                    e.printStackTrace();
                    retval = 8;
                    break outer;
                }

                end = time();
            }
            while ( end - strt < 10000 );
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();

            if ( retval != -1 )
                return retval;
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "BTRandom: error closing tcp socket" );

            if ( retval == -1 )
                return 9;
            else
                return retval;

        }

        Log.v( TAG, "BTRandom: everything great " );
        return 10;

    }


    // Reachability

    class Reachability extends Thread {



        int index;
        public Reachability( int i ) {
            super();
            index = i;
        }


        public void run() {

            Log.v( TAG, "indexz is " + index );
            REACHB[ index ] = false;
            REACHBst[ index ] = 'o';
            Socket tcpSocket = null;
            DataOutputStream os = null;
            DataInputStream is = null;

            try {
                tcpSocket = new Socket();
                SocketAddress remoteAddr = new InetSocketAddress( ReachserverIP, ports[ index ] );
                tcpSocket.connect( remoteAddr, 2000 );
                os = new DataOutputStream( tcpSocket.getOutputStream() );
                is = new DataInputStream( tcpSocket.getInputStream() );
                tcpSocket.setSoTimeout( 2000 );
            }
            catch ( Exception e ) {
                //TODO
                REACHBst[ index ] = 'c';
                Log.v( TAG, "Reachability: cannot resolve host for port " + ports[ index ] );

            }

            if ( tcpSocket == null || os == null || is == null ) {
                //TODO
                REACHBst[ index ] = 'c';
                Log.v( TAG, "Reachability: cannot open tcp socket to port " + ports[ index ] );
            }

            else {

                try {
                    byte [] message = "hello".getBytes();
                    os.write( message );
                    byte[] buffer = new byte[ 1000 ];
                    int read_bytes = is.read( buffer, 0, 1000 );

                    if ( read_bytes != -1 ) {
                        String reply = new String( buffer, 0, read_bytes );

                        if ( reply.equals( "hello" ) ) {
                            REACHB[ index ] = true;
                        }
                        else {
                            REACHBst[ index ] = 'd';
                        }
                    }
                    else {
                        REACHBst[ index ] = 'd';
                    }
                }
                catch ( Exception e ) {
                    // TODO Auto-generated catch block
                    REACHBst[ index ] = 'd';
                    e.printStackTrace();
                }

                try {
                    os.close();
                    is.close();
                    tcpSocket.close();
                }
                catch ( Exception e ) {
                    REACHBst[ index ] = 'd';
                }
            }

            rports++;
        }




    }

    // http



    int HttpNatExistence( String serverIP ) {

        localip = null;
        NATexistence = true;
        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        SocketAddress remoteAddr = null;

        try {
            tcpSocket = new Socket();
            remoteAddr = new InetSocketAddress( serverIP, PORT_WHOAMI );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );

        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "HttpNatExistence: cannot resolve tcp host" );
            return 2;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "HttpNatExistence: cannot get the I/O for tcp connection " + remoteAddr.toString() );
            return 3;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "HttpNatExistence: tckpSocket or os or is null" );
            return 4;
        }

        seenip = null ;
        int retval = -1;
outer: {
            try {
                byte [] messag = prefix.getBytes();
                os.write( messag );
            }
            catch ( Exception e3 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "MeasureUplinkTput: error in sending prefix" );
                retval = 4;
                break outer;
            }

            localip = tcpSocket.getLocalAddress().getHostName();

            try {
            	/*
            	 * mhayter
            	 * byte[] message = "WHO:WHOAMI?".getBytes();
            	 * os.write( message );
                */
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    retval = 5;
                    break outer;
                }

                seenip = new String( buffer, 0, read_bytes );

            }
            catch ( Exception e ) {
                Log.v( TAG, "HttpNatExistence: problem in sending or receiving " + e.getMessage() );
                retval = 5;
                break outer;
            }


        }

        try {
            tcpSocket.close();
            os.close();
            is.close();

            if ( retval != -1 )
                return retval;
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "HttpNatExistence: error closing tcp socket" );

            if ( retval != -1 )
                return retval;
            else
                return 6;

        }

        if ( localip != null && seenip != null ) {
            if ( localip.equals( seenip ) ) {
                NATexistence = false;
                return 7;
            }
            else {
                NATexistence = true;
                return 8;
            }
        }
        else {
            return 6;
        }
    }


    int HTTPptosUp( String serverIP ) {
        btblockedstage = "S";
        int nofPackets = 0;
        char [] cs = new char[ 1000 ];
        int [] size = new int[ 1000 ];
        boolean timeoutflag = false;
        // reading size file

        try {
            if ( checkstop() ) {
                return 1;
            }

            InputStream reader = null;
            reader = this.getResources().openRawResource( R.raw.https );
            byte[] buffer = new byte[ 1000 ];

            while ( reader.available() != 0 ) {
                if ( checkstop() ) {
                    return 1;
                }

                String line = "";
                char c;

                do {
                    reader.read( buffer, 0, 1 );
                    c = ( char ) buffer[ 0 ];

                    if ( c != '\n' )
                        line += c;
                }
                while ( c != '\n' );

                cs[ nofPackets ] = line.charAt( 0 );

                String temp = "";

                int j = 0;

                String leng = "" + line.charAt( 2 );

                int l = new Integer( leng );

                while ( j < l ) {
                    temp += line.charAt( 3 + j );
                    j++;
                }

                size[ nofPackets++ ] = new Integer( temp );
            }
        }
        catch ( Exception e ) {
            //TODO Auto-generated catch block
            Log.v( TAG, "BTptosU: error in opening size file " + e.getMessage() );
            return 1;
        }

        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;

        try {
            if ( checkstop() ) {
                return 1;
            }

            tcpSocket = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress( serverIP, PORT_HTTP );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );

        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "BTptosU: cannot resolve tcp host" );
            btblockedstage = "SYN";
            return 2;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "BTptosU: cannot get the I/O for tcp connection" );
            btblockedstage = "SYN";
            return 3;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "BTptosU: tckpSocket or os or is null" );
            btblockedstage = "SYN";
            return 4;
        }

outer: {
            if ( checkstop() ) {
                break outer;
            }

            InputStream reader = null;

            try {
                reader = this.getResources().openRawResource( R.raw.http );
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "bt file not found" );
                break outer;
            }

            //sending prefix and getting reply
            String aux = ".............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................";

            try {
                String pref = prefix + aux;
                byte [] message = pref.getBytes();
                os.write( message );
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "PrefixOK" ) == false ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosU: error sending prefix" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            try {
                byte [] message = ( "UplinkStart" + aux ).getBytes();
                os.write( message );
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosU: error sending uplink" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            byte [] buf = new byte[ 10000 ];
            //sending actual data now

            try {
                Thread.sleep( 2000 );
            }
            catch ( InterruptedException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            if ( checkstop() ) {
                break outer;
            }

            long strt, end;
            strt = time();

            for ( int i = 0;i < nofPackets;i++ ) {
                if ( checkstop() ) {
                    break outer;
                }

                if ( cs[ i ] == 's' ) {
                    int tol = size[ i ];

                    try {
                        if ( tol > 10000 ) {
                            do {
                                if ( checkstop() ) {
                                    break outer;
                                }

                                reader.read( buf, 0, 1000 );
                                tol -= 1000;
                                os.write( buf, 0, 1000 );
                                end = time();

                                if ( end - strt > 8000 ) {
                                    timeoutflag = true;
                                    break outer;
                                }
                            }
                            while ( tol > 10000 );
                        }

                        reader.read( buf, 0, tol );
                        os.write( buf, 0, tol );
                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();

                        if ( i == 1 )
                            btblockedstage = "Hdsk";

                        if ( i == 3 )
                            btblockedstage = "Cont";

                        if ( i >= 5 )
                            btblockedstage = "Req";

                        Log.v( TAG, "BTptosU: error sending actual data " + e.getMessage() );

                        break outer;
                    }
                }
                else {
                    try {
                        byte[] buffer = new byte[ 1000 ];
                        int len = 0;

                        if ( size[ i ] > 1000 ) {
                            do {
                                if ( checkstop() ) {
                                    timeoutflag = true;
                                    break outer;
                                }

                                int read_bytes = is.read( buffer, 0, 1000 );
                                len += read_bytes;

                                if ( read_bytes <= 0 ) {

                                    if ( i == 0 )
                                        btblockedstage = "Hdsk";

                                    if ( i == 2 )
                                        btblockedstage = "Cont";

                                    if ( i >= 4 )
                                        btblockedstage = "Piece";

                                    break outer;
                                }
                            }
                            while ( size[ i ] - len > 1000 );
                        }

                        do {
                            if ( checkstop() ) {
                                timeoutflag = true;
                                break outer;
                            }

                            int read_bytes = is.read( buffer, 0, size[ i ] - len );
                            len += read_bytes;

                            if ( read_bytes <= 0 ) {
                                if ( i == 0 )
                                    btblockedstage = "Hdsk";

                                if ( i == 2 )
                                    btblockedstage = "Cont";

                                if ( i >= 4 )
                                    btblockedstage = "Piece";

                                break outer;
                            }
                        }
                        while ( size[ i ] - len != 0 );

                        end = time();

                        if ( end - strt > 8000 ) {
                            timeoutflag = true;
                            break;
                        }

                        //String reply = new String(buffer,0,read_bytes);
                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        Log.v( TAG, "BTptosU: error receiving actual data " + e.getMessage() );
                        e.printStackTrace();

                        if ( i == 0 )
                            btblockedstage = "Hdsk";

                        if ( i == 2 )
                            btblockedstage = "Cont";

                        if ( i >= 4 )
                            btblockedstage = "Piece";

                        break outer;
                    }
                }
            }
        }

        if ( timeoutflag ) {
            try {
                byte [] message = "UplinkDone".getBytes();
                os.write( message );

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "E";
                Log.v( TAG, "BTptosD: error sending downlink" );
                return 12;
            }
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "BTptosU: error closing tcp socket" );
            btblockedstage = "E";
            return 13;

        }

        if ( btblockedstage.equals( "S" ) ) {
            btblockedstage = "E";
            Log.v( TAG, "BTptosU: everything great " );
        }

        return 14;

    }

    int HTTPptosDown( String serverIP ) {
        btblockedstage = "S";
        int nofPackets = 0;
        List<Integer> list = new ArrayList<Integer>();
        char [] cs = new char[ 1000 ];
        int [] size = new int[ 1000 ];
        int l = 0;
        boolean timeoutflag = false;
        // reading size file

        try {
            if ( checkstop() ) {
                return 1;
            }

            InputStream reader = null;
            reader = this.getResources().openRawResource( R.raw.https );
            byte[] buffer = new byte[ 1000 ];

            while ( reader.available() != 0 ) {
                if ( checkstop() ) {
                    return 1;
                }

                String line = "";
                char c;

                do {
                    reader.read( buffer, 0, 1 );
                    c = ( char ) buffer[ 0 ];

                    if ( c != '\n' )
                        line += c;
                }
                while ( c != '\n' );

                cs[ nofPackets ] = line.charAt( 0 );

                String temp = "";

                int j = 0;

                String leng = "" + line.charAt( 2 );

                int lk = new Integer( leng );

                while ( j < lk ) {
                    temp += line.charAt( 3 + j );
                    j++;
                }

                size[ nofPackets++ ] = new Integer( temp );
            }
        }
        catch ( Exception e ) {
            //TODO Auto-generated catch block
            Log.v( TAG, "BTptosD: error in opening size file " + e.getMessage() );
            return 1;
        }

        Socket tcpSocket = null;
        DataOutputStream os = null;
        DataInputStream is = null;

        try {
            if ( checkstop() ) {
                return 1;
            }

            tcpSocket = new Socket();

            SocketAddress remoteAddr = new InetSocketAddress( serverIP, PORT_HTTP );
            tcpSocket.connect( remoteAddr, 4000 );
            os = new DataOutputStream( tcpSocket.getOutputStream() );
            is = new DataInputStream( tcpSocket.getInputStream() );
            tcpSocket.setSoTimeout( 4000 );

        }
        catch ( UnknownHostException e ) {
            //TODO
            Log.v( TAG, "BTptosD: cannot resolve tcp host" );
            btblockedstage = "SYN";
            return 2;
        }
        catch ( Exception e ) {
            //TODO
            Log.v( TAG, "BTptosD: cannot get the I/O for tcp connection" );
            btblockedstage = "SYN";
            return 3;
        }

        if ( tcpSocket == null || os == null || is == null ) {
            //TODO
            Log.v( TAG, "BTptosD: tckpSocket or os or is null" );
            btblockedstage = "SYN";
            return 4;
        }

outer: {
            if ( checkstop() ) {
                break outer;
            }

            InputStream reader = null;

            try {
                reader = this.getResources().openRawResource( R.raw.http );
            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                Log.v( TAG, "bt file not found" );
                break outer;
            }

            String aux = ".............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................";

            //sending prefix and getting reply

            try {
                String pre = prefix + aux;
                byte [] message = pre.getBytes();
                os.write( message );
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "PrefixOK" ) == false ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosD: got wrong reply for prefix" );
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosD: error sending prefix" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            try {
                byte [] message = ( "Downlink" + aux ).getBytes();
                os.write( message );
                byte[] buffer = new byte[ 1000 ];
                int read_bytes = is.read( buffer, 0, 1000 );

                if ( read_bytes <= 0 ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosU: got wrong reply for prefix" );
                    break outer;
                }

                String reply = new String( buffer, 0, read_bytes );

                if ( reply.equals( "DownlinkOK" ) == false ) {
                    btblockedstage = "Hdsk";
                    Log.v( TAG, "BTptosD: got wrong reply for downlink" );
                    break outer;
                }

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "Hdsk";
                Log.v( TAG, "BTptosD: error sending downlink" );
                break outer;
            }

            if ( checkstop() ) {
                break outer;
            }

            byte [] buf = new byte[ 10000 ];
            //sending actual data now
            int count = 0;

            try {
                Thread.sleep( 2000 );
            }
            catch ( InterruptedException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            long strt, end;
            strt = time();

            if ( checkstop() ) {
                break outer;
            }

            for ( int i = 0;i < nofPackets;i++ ) {
                if ( checkstop() ) {
                    break outer;
                }

                if ( cs[ i ] == 'c' ) {
                    try {
                        reader.read( buf, 0, size[ i ] );
                        os.write( buf, 0, size[ i ] );

                        count++;
                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Log.v( TAG, "BTptosD: error sending actual data " + e.getMessage() );

                        if ( i == 0 )
                            btblockedstage = "Hdsk";

                        if ( i == 2 )
                            btblockedstage = "Cont";

                        if ( i >= 4 )
                            btblockedstage = "Req";

                        break outer;
                    }
                }
                else {
                    try {
                        byte[] buffer = new byte[ 1000 ];
                        int len = 0;

                        if ( size[ i ] > 1000 ) {
                            do {
                                if ( checkstop() ) {
                                    timeoutflag = true;
                                    break outer;
                                }

                                int read_bytes = is.read( buffer, 0, 1000 );
                                len += read_bytes;

                                if ( read_bytes <= 0 ) {
                                    Log.v( TAG, "read bytes -1" );

                                    if ( i == 1 )
                                        btblockedstage = "Hdsk";

                                    if ( i == 3 )
                                        btblockedstage = "Cont";

                                    if ( i >= 5 )
                                        btblockedstage = "Piece";

                                    break outer;
                                }

                                end = time();

                                if ( end - strt > 8000 ) {
                                    timeoutflag = true;
                                    break outer;
                                }
                            }
                            while ( size[ i ] - len > 1000 );
                        }

                        do {
                            if ( checkstop() ) {
                                timeoutflag = true;
                                break outer;
                            }

                            int read_bytes = is.read( buffer, 0, size[ i ] - len );

                            if ( read_bytes <= 0 ) {
                                if ( read_bytes <= 0 ) {
                                    if ( i == 1 )
                                        btblockedstage = "Hdsk";

                                    if ( i == 3 )
                                        btblockedstage = "Cont";

                                    if ( i >= 5 )
                                        btblockedstage = "Piece";

                                    break outer;
                                }
                            }

                            len += read_bytes;

                        }
                        while ( size[ i ] - len != 0 );

                        end = time();

                        if ( end - strt > 8000 ) {
                            timeoutflag = true;
                            break outer;
                        }

                        //String reply = new String(buffer,0,read_bytes);
                    }
                    catch ( Exception e ) {
                        // TODO Auto-generated catch block
                        Log.v( TAG, "BTptosD: error receiving actual data " + e.getMessage() );
                        e.printStackTrace();

                        if ( i == 1 )
                            btblockedstage = "Hdsk";

                        if ( i == 3 )
                            btblockedstage = "Cont";

                        if ( i >= 5 )
                            btblockedstage = "Piece";

                        break outer;

                    }
                }
            }
        }

        if ( timeoutflag ) {
            try {
                byte [] message = "DownlinkDone".getBytes();
                os.write( message );

            }
            catch ( Exception e1 ) {
                // TODO Auto-generated catch block
                btblockedstage = "E";
                Log.v( TAG, "BTptosD: error sending downlink" );
            }
        }

        try {
            tcpSocket.close();
            os.close();
            is.close();
        }
        catch ( Exception e2 ) {
            // TODO Auto-generated catch block
            Log.v( TAG, "BTptosD: error closing tcp socket" );
            return 10;

        }

        if ( btblockedstage.equals( "S" ) ) {
            btblockedstage = "E";
            Log.v( TAG, "BTptosD: everything great " );
        }

        return 11;

    }

}